Multicast UDP

11.3 Multicast UDP

Multicasting is where a message can travel to more than one destination at the same time. This can provide significant increases in efficiency where there is more than one recipient of the data being sent. It is ideally suited to networks where all clients and servers are on the same LAN, and it is routable on the Internet, but is only supported by some service providers.

The first audio multicast took place in 1992, followed one year later by the first video multicast. Nowadays, multicast UDP is used in products such as Symantec Ghost to provide remote software installations on multi- ple hosts simultaneously. It is also used to broadcast video footage of popu- lar events over the Internet.

11.3.1 Multicast basics

From a programmer’s perspective, the difference between point-to-point UDP and multicast UDP is minimal. In .NET, we use the UDPClient object and call the JoinMulticastGroup() method, passing to it a multicast

IP address. We can then send and receive packets using the same methods as we would with a standard UDP connection.

A multicast IP address is one that lies in the range 224.0.0.0 to 239.255.255.255. Unfortunately, you can’t pick any multicast IP address arbitrarily because there are some restrictions. The IANA controls multicast IP addresses, so you should consult RFC 3171 and the IANA Web site for a definitive list. Never use a multicast IP address that is already assigned to a well-known purpose, such as the following:

224.0.0.0 to 224.0.0.255: The Local Network Control Block is non- routable and cannot travel over the Internet. These addresses have well-known purposes (e.g., DHCP is on address 224.0.0.12).

224.0.1.0 to 224.0.1.255: The Internetwork Control Block is routable, but these addresses have special uses. Network time proto- col (NTP) is on address 224.0.1.1, and WINS is on address 224.0.1.24.

239.0.0.0 to 239.255.255.255: The scope-relative addresses are not routable, but they have no special purpose and can be used freely for experimental purposes.

11.3 Multicast UDP 283

It is possible to request a globally unique multicast IP address from the IANA. Initially, you should use an experimental multicast address such as 234.5.6.11 or obtain a leased multicast address from multicast address dynamic client allocation protocol (MADCAP), as defined in RFC 2730.

If other people are using the same multicast address as you, you may receive stray packets that could corrupt the data you are trying to transmit. If you are broadcasting exclusively to a LAN, use a scope-relative address.

When broadcasting on a WAN (but not the Internet), you can limit the TTL of the packet to less than 63. TTL prevents a packet from being routed indefinitely. Every hop decreases the TTL by one. When the TTL reaches zero, the packet is discarded. This can confine a packet to a geo- graphic area and also prevents multicast avalanches, which occur when packets are replicated exponentially and end up clogging routers all over the Internet.

11.3.2 Multicast routing

Multicast UDP may be the first non-P2P protocol to be accessible pro- grammatically, but there is nothing new in protocols that broadcast rather than going from A to B. Routing protocols such as RIP and OSPF do not have set endpoints; rather, they percolate through networks in all directions at once. In fact, it would be a paradox if a routing protocol needed to be routed from point to point. The technique is not limited to routing proto- cols (e.g., BOOTP [bootstrap] and ARP are other examples of nondirec- tional protocols).

The biggest limitation of network broadcasts is that they generally only work within the same LAN and cannot be routed across the Internet. Multi- cast UDP goes partway toward solving this problem. It is true that not every- one can send or receive multicasts to or from the Internet. Multicast data does have a tendency to flood networks, so not all service providers want to

be bombarded with unsolicited data. To enable service providers who do accept multicast to communicate, the multicast backbone (MBONE) was developed. This links multicast-compatible providers together via point-to- point channels in non-multicast-compatible networks. It currently spans more than 24 countries, mostly in academic networks.

Multicast implies that data travels in all directions at once (floods), but in practice, it is not the UDP packets that flood, but multicast routing pro- tocol packets that do this job for them. There are three multicast routing protocols: distance vector multicast routing (DVMRP), multicast open shortest path first (MOSPF), and protocol independent multicast (PIM).

Chapter 11

284 11.3 Multicast UDP

A subscriber to a multicast will issue an Internet group management proto- col (IGMP) packet to register its interest in receiving messages. This proto- col is also used to leave groups.

There is no equivalent multicast TCP because of the constant one-to- one handshaking that is required. This causes some difficulties for applica- tion developers because data sent by UDP can be corrupted as a result of packet loss, duplication, and reordering. This problem can be counteracted by inserting headers in the data containing a sequence number, which the client can reorganize or request a once-off TCP/IP transfer of the missing packet from the server.

Similarly, it is difficult to implement public/private key security via mul- ticast because every client would have a different public key. The IETF is scheduled to publish a standard security mechanism over multicast (MSEC) to address this issue.

11.3.3 Implementing multicast

Before you can implement a multicast-enabled application, you should ensure that your Internet connection supports multicast traffic and is con- nected to the MBONE network.

This example consists of two applications: a sender and a receiver. We start with the implementation of the sender. Open a new project in Visual Studio .NET and add three textboxes: tbMulticastGroup , tbPort , and tbMessage . You will also require a button named btnSend .

Click on the Send button, and add the following code:

C#

private void btnSend_Click(object sender, System.EventArgs e) {

send(tbMulticastGroup.Text , int.Parse(tbPort.Text), tbMessage.Text );

VB.NET

Private Sub btnSend_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) send(tbMulticastGroup.Text,Integer.Parse(tbPort.Text), _

tbMessage.Text) End Sub

11.3 Multicast UDP 285

Multicast operation can be performed at both the socket level and Udp- Client level. To illustrate both techniques, the sender (client) will be imple- mented using sockets, whereas the receiver will be implemented using the UdpClient object. Before sending or receiving from a multicast group, it is necessary to join the group. This is done in the example below using the socket option AddMembership .

In the same way as if the socket was operating in point-to-point (uni- cast) mode, the remote endpoint must be specified with both a port and an IP address. The IP address in this case must be valid and within the multi- cast range (224.0.0.0 to 239.255.255.255). The TTL specifies how far the packet can travel; in this case, it is set to the maximum, 255.

The next step is to implement the Send function as follows:

C#

public void send(string mcastGroup, int port, string message) {

IPAddress ip=IPAddress.Parse(mcastGroup); Socket s=new Socket(AddressFamily.InterNetwork,

SocketType.Dgram, ProtocolType.Udp); s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip)); s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 255); byte[] b; b = Encoding.ASCII.GetBytes(message); IPEndPoint ipep=new IPEndPoint( IPAddress.Parse(mcastGroup), port); s.Connect(ipep); s.Send(b,b.Length,SocketFlags.None); s.Close();

VB.NET

Public Sub send(ByVal mcastGroup As String, _

ByVal port As Integer, ByVal message As String) Dim ip As IPAddress = IPAddress.Parse(mcastGroup) Dim s As Socket = New Socket(AddressFamily.InterNetwork, _ SocketType.Dgram, ProtocolType.Udp) s.SetSocketOption(SocketOptionLevel.IP, _

Chapter 11

286 11.3 Multicast UDP

SocketOptionName.AddMembership, New MulticastOption(ip)) s.SetSocketOption(SocketOptionLevel.IP, _ SocketOptionName.MulticastTimeToLive, 255) Dim b As Byte()

b = Encoding.ASCII.GetBytes(Message) Dim ipep As IPEndPoint = New _ IPEndPoint(IPAddress.Parse(mcastGroup), port) s.Connect(ipep) s.Send(b, b.Length, SocketFlags.None) s.Close()

End Sub

This code uses sockets rather than streams to send multicast data. Sev- eral parameters need to be applied to the newly created code in order for it to operate effectively in multicast mode. First, the protocol type is set to UDP with ProtocolType.Udp because this is the underlying protocol for all

multicast broadcasts.

A socket option is then set such that the socket will request to join the specified group. The option SocketOptionName.AddMembership indicates that the socket is attaching to a multicast group. The final parameter is the TTL; in this case, the TTL is 255, which effectively means that the packet(s) can travel anywhere in the world.

The message, which is in string format, is converted to a byte array. The endpoint is set to the multicast address on the port specified. The socket then connects to the endpoint, sends the byte array, and then disconnects.

To complete the program, add the required namespaces at the top of the code:

C#

using System.Text; using System.Net; using System.Net.Sockets;

VB.NET

Imports System.Text Imports System.Net Imports System.Net.Sockets

11.3 Multicast UDP 287

The next step is to code the multicast receiver. Open a new project in Visual Studio .NET and draw a textbox named tbMessages with multi- line set to true on the form.

C#

private void Form1_Load(object sender, System.EventArgs e) {

Thread thdReceiver = new Thread(new ThreadStart(receiverThread)); thdReceiver.Start();

VB.NET

Private Sub Form1_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Dim thdReceiver As Thread thdReceiver = New Thread(New ThreadStart _

(AddressOf receiverThread)) thdReceiver.Start() End Sub

The receiving thread will remain in an infinite loop awaiting new data. It is therefore run in a separate thread named recieverThread() .

In this case, the multicast functionality is implemented using the UdpClient object. Membership to the group is obtained by calling the JoinMulticastGroup . Again the TTL and port details must be specified.

Enter the following code to finish this application:

C#

public void receiverThread() {

UdpClient client = new UdpClient(5000); IPAddress group = IPAddress.Parse("224.5.4.6"); int timeToLive = 255; int port = 5000; client.JoinMulticastGroup(group, timeToLive); IPEndPoint remoteEP = new IPEndPoint(group, port); while (true) {

IPEndPoint ep = null; Chapter 11

288 11.3 Multicast UDP

byte[] buffer = client.Receive(ref ep); string message = Encoding.ASCII.GetString(buffer); this.tbMessages.Text += message + "\n";

VB.NET

Public Sub receiverThread() Dim client As UdpClient = New UdpClient(5000) Dim group As IPAddress = IPAddress.Parse("224.5.4.6") Dim timeToLive As Integer = 255 Dim port As Integer = 5000 client.JoinMulticastGroup(group, timeToLive) Dim remoteEP As IPEndPoint = New IPEndPoint(group,port) Do

Dim ep As IPEndPoint = Nothing Dim buffer() As Byte = client.Receive( ep) Dim message as String = _ System.Text.Encoding.ASCII.GetString(buffer) Me.tbMessages.Text += message + vbcrlf

Loop End Sub

This code uses a higher level of abstraction than the sender and imple- ments a multicast receiver using UdpClient objects rather than bare sockets. In much the same way as you would receive standard UDP packets, the UdpClient is set to listen on a specified port (in this case, 5000) by passing the port number to the constructor. Where it differs is when JoinMulti- castGroup is called. This method is passed an IPAddress object that holds the multicast IP address and the TTL value for any packets sent. The pro- gram goes into an infinite loop at this point, receiving arrays of bytes from whomever happens also to be transmitting on that multicast IP address. These byte arrays are then converted into strings and displayed on-screen.

To finish this code, add the required namespaces as follows:

C#

using System.Threading; using System.Net; using System.Net.Sockets; using System.Text;

11.4 Data compression 289

Figure 11.1

Multicast UDP client and server.

VB.NET

Imports System.Threading Imports System.Net Imports System.Net.Sockets Imports System.Text

To test this application, run both the sender and receiver from Visual Studio .NET. Set the group address on the sender to 224.5.6.7 and the port to 5000, type in a short message, and press send. You will see the text appearing in the receiver application (Figure 11.1). It should be possible to open multiple instances of the receiver application and have them all receive the same text simultaneously.