Surprisingly, you don't need to do any more to the sender to transmit a multicast message. Currently, all multicasting is UDP only (IPv6 has included support for multicast TCP). To send a multicast message, you just transmit to one of the multicast addresses (224.0.0.023184.108.40.206). If you're connected to the Internet, be careful when you choose the destination address, because some addresses in this range are "global" (may end up on the wide area network). Sending test messages all over the world is somewhat network-unfriendly.
Unlike the sender, a receiver that's listening to a multicast address has to configure its socket a little more. While the program's socket has its own address and port, to get multicast messages from the network you need to use setsockopt() (set socket option) to subscribe to the service. Like the bind() system call, this call requires the address and network interface. The following code sample demonstrates how to fill the data structure and set the socket option:
inet_aton("220.127.116.11", &mreq.imr_multiaddr); /*select address*/ mreq.imr_interface.s_addr = INADDR_ANY; /* any interface */ setsockopt(sd, SOL_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq);
If successful, this option tells the routers within the network scope to watch for and redirect messages with the specified address. Just as with bind(), you can specify a particular local host address through which the program accepts the messages.
Multicasting works through the routers. The routers are responsible for tracking subscriptions and forwarding all messages that match the selected address. From the instant when the program completes the subscription, the operating system receives and forwards every message that matches the address. What can be confusing for the programmer is that the program can't distinguish between a multicast message and a directed P2P message.
You also need to be aware of an important issue about ports. The operating system still recognizes UDP's use of ports, so you need to select a port using bind() just as with normal P2P messaging, described earlier in this article. From the perspective of multicast programming support, you simply add the subscription statements after calling bind().
Multicasting and ports present a significant limitation to multicasting's design: From the point that you subscribe, you get all messages for that address, regardless of the port selection. The operating system on your host filters out all port-mismatched messages. This means that you can potentially and significantly lose network performance due to flooding (overflow of unwanted/unsolicited messages). For example, a program that sets its port to 5000 and then subscribes to a multicast address that has hosts sending messages to ports 5000, 10240, and 34000 gets all transmissions from the routers, not just those for port 5000.