Multicast

Whenever there is need to distribute same data to multiple applications over network I tend to see same thing. Everybody just makes broadcast socket. That is usually wrong way to do it.

From the very beginning of IP, there is special class called multicast addresses. Idea is simple: you “join” multicast address and whatever you send to it is received by everybody else who joined.

While this might seem a lot like broadcast, it is not the same thing. If you have network of 100 computers and only two need to talk, broadcast will send same data to 100 of them anyway. In multicast case switch can optimize this and send data only to two computers that need it.

Even in case of dumb switch which behaves with multicast in same manner as with broadcast, there is benefit. Since multicast addresses reside in completely different range, there is no fear that we will interfere with any normal socket that is listening on same port. Yes, we might stumble at another multicast group by accident but chances are pretty slim.

Creation of multicast socket is quite similar to creation of any other socket:

this.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
this.Socket.Bind(new IPEndPoint(IPAddress.Any, 65535));
this.Socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.192.0.1"), IPAddress.Any));

As you can see, only real difference is in additional socket option that adds our socket to multicast group (do not forget do remove it on application exit).

And that is it. Everything else works as it would with “normal” socket.

Code example is available for download.

P.S. For this example I use multicast address of 239.192.0.1. You might want to change this to something not as usual as this (but still in 239.192.0.0 range).