Receiving IPv4 Multicast Datagrams
Before a host can receive IP multicast datagrams, the host must become a member of one or more IP multicast groups. A process can ask the host to join a multicast group by using the following socket option:
struct ip_mreq mreq; setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq))
where mreq
is the structure:
struct ip_mreq { struct in_addr imr_multiaddr; /* multicast group to join */ struct in_addr imr_interface; /* interface to join on */ }
Each membership is associated with a single interface. You can join
the same group on more than one interface. Specify the imr_interface
address
as INADDR_ANY
to choose the default multicast interface.
You can also specify one of the host's local addresses to choose a particular
multicast-capable interface.
To drop a membership, use:
struct ip_mreq mreq; setsockopt(sock, IPPROTO_IP, IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq))
where mreq
contains the same values used to add the
membership. Closing a socket or killing the process that holds the socket
drops the memberships associated with that socket. More than one socket can
claim a membership in a particular group, and the host remains a member of
that group until the last claim is dropped.
If any socket claims membership in the destination group of the datagram,
the kernel IP layer accepts incoming multicast packets. A given socket's receipt
of a multicast datagram depends on the socket's associated destination port
and memberships, or the protocol type for raw sockets. To receive multicast
datagrams sent to a particular port, bind to the local port, leaving the local
address unspecified, such as INADDR_ANY
.
More than one process can bind to the same SOCK_DGRAM
UDP port if the
bind
is preceded by:
int one = 1; setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))
In this case, every incoming multicast or broadcast UDP datagram destined
for the shared port is delivered to all sockets bound to the port. For backwards
compatibility reasons, this delivery does not apply to
incoming unicast datagrams. Unicast datagrams are never delivered to more
than one socket, regardless of how many sockets are bound to the datagram's
destination port. SOCK_RAW
sockets do not require the SO_REUSEADDR
option to share a single IP protocol type.
The definitions required for the new, multicast-related socket options
are found in <netinet/in.h>
. All IP addresses are passed
in network byte-order.