The use of Internet Protocol (IP) multicasting enables a message to be transmitted to a group of hosts, instead of having to address and send the message to each group member individually. Internet addressing provides for Class D addressing that is used for multicasting.
When a datagram socket is defined, the setsockopt subroutine can be modified. To join or leave a multicast group, use the setsockopt subroutine with the IP_ADD_MEMBERSHIP or IP_DROP_MEMBERSHIP flags. The interface that is used and the group used are specified in an ip_mreq structure that contains the following fields:
struct ip_mreq{ struct in_addr imr.imr_interface.s_addr; struct in_addr imr.imr_multiaddr.s_addr; }
The in_addr structure is defined as:
struct in_addr{ ulong s_addr; }
In order to send to a multicasting group it is not necessary to join the groups. For receiving transmissions sent to a multicasting group, membership is required. For multicast sending, use an IP_MULTICAST_IF flag with the setsockopt subroutine. This specifies the interface to be used. It may be necessary to call the setsockopt subroutine with the IP_MULTICAST_LOOP flag in order to control the loopback of multicast packets. By default, packets are delivered to all members of the multicast group including the sender, if it is a member. However, this can be disabled with the setsockopt subroutine using the IP_MULTICAST_LOOP flag.
The setsockopt subroutine flags that are required for multicast communication and used with the IPPROTO_IP protocol level follow:
The following examples demonstrate the use of the setsockopt function with the protocol level set to Internet Protocol (IPPROTO_IP).
To mark a socket for sending to a multicast group on a particular interface:
struct ip_mreq imr; setsockopt(s, IPPROTO_IP, IP_MULTICAST_IF, &imr.imr_interface.s_addr, sizeof(struct in_addr));
To disable the loopback on a socket:
char loop = 0; setsockopt(s, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(char));
To allow address reuse for binding multiple multicast applications to the same IP group address:
int on = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int));
To join a multicast group for receiving:
struct ip_mreq imr; setsockopt(s, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(struct ip_mreq));
struct ip_mreq imr; setsockopt(s, IPPROTO_IP, IP_DROP_MEMBERSHIP, &imr, sizeof(struct ip_mreq));
The getsockopt function can also be used with the multicast flags to obtain information about a particular socket.