Receiving IP Multicast Datagrams
CyberData Corporation
930367H
Operations Guide
53
C.2 Receiving IP Multicast Datagrams
Before a host can receive IP multicast datagrams, it 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 following structure:
struct ip_mreq {
struct in_addr imr_multiaddr;/* multicast group to join */
struct in_addr imr_interface;/* interface to join on */
}
Every membership is associated with a single interface, and it is possible to join the same group on
more than one interface. "imr_interface" should be INADDR_ANY to choose the default multicast
interface, or one of the host's local addresses to choose a particular (multicast-capable) interface. Up
to IP_MAX_MEMBERSHIPS (currently 20) memberships may be added on a single socket.
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 as used to add the membership. The memberships
associated with a socket are also dropped when the socket is closed or the process holding the socket
is killed. However, more than one socket may claim a membership in a particular group, and the
host will remain a member of that group until the last claim is dropped.
The memberships associated with a socket do not necessarily determine which datagrams are
received on that socket. Incoming multicast packets are accepted by the kernel IP layer if any socket
has claimed a membership in the destination group of the datagram; however, delivery of a
multicast datagram to a particular socket is based on the destination port (or protocol type, for raw
sockets), just as with unicast datagrams. To receive multicast datagrams sent to a particular port, it is
necessary to bind to that local port, leaving the local address unspecified (i.e., INADDR_ANY).
More than one process may 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 to the shared port is
delivered to all sockets bound to the port. For backwards compatibility reasons, THIS 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.