The members associated with a socket do not necessarily determine which datagrams are received by 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. To receive multicast datagrams sent to a particular port, it is necessary to bind to that local port, leaving the local address unspecified, that is, INADDR_ANY.
More than one process may bind to the same SOCK_DGRAM UDP port if the bind call is preceded by the following code.
int one = 1;
getsockopt(
sock,
SOL_SOCKET,
SO_REUSEADDR,
(char *)&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.
The getsockopt function retrieves the current value for a socket option associated with a socket of any type, in any state, and stores the result in optval. Options can exist at multiple protocol levels, but they are always present at the uppermost socket level. Options affect socket operations. If the option was never set with setsockopt, then getsockopt returns the default value for the option. The definitions required for the multicast-related socket options are located in the Winsock.h file. All IP addresses are passed in network byte-order.
For an example of an application receiving a multicast datagram, see Receiving an IP Multicast Datagram Sample.