What Is Broadcasting?



What Is Broadcasting?

IP broadcasting is used by network devices to send a single packet of information that can be accessible by every device on the network. Because TCP communication requires that two devices have a dedicated connection, it is not possible to send broadcast messages in a strictly TCP environment. Instead, UDP packets must be used because that protocol has the capability of sending messages without a specific connection being defined.

Local versus Global Broadcasts

Broadcast messages contain a special destination IP address. The IP address format allows for two types of broadcast message addresses: local broadcasts and global broadcasts.

Network programmers use the local broadcast address to send a broadcast message destined for all devices on a particular subnet. The idea is to localize a broadcast message so that other networks are not affected by the broadcast.

As discussed in Chapter 2, “IP Programming Basics,” an IP address is divided into two parts, a network address and a host address. The standard network address part makes up the first part of the local broadcast address, and all 1s are used for the host part of the address (which is the decimal value 255 in the address octet). This is demonstrated in Figure. Thus, for the class B network 192.168.0.0, using a subnet mask of 255.255.0.0, the local broadcast address would be 192.168.255.255.

Click To expand
Figure: The IP network and host address parts of a local broadcast address

Similarly, if the subnet is further divided using a subnet mask of 255.255.255.0, each subnet would have its own local broadcast address. The subnet 192.168.1.0 would have a broadcast address of 192.168.1.255, and so on up to the subnet 192.168.254.0, which would have the broadcast address 192.168.254.255.

The global broadcast was originally intended to allow a device to send a packet to all devices on an internetwork. It uses all 1s in the IP address, creating an address of 255.255.255.255. This special broadcast address indicates that the destination of the packet is all devices on all networks accessible from the device sending the message.

The vast size and burgeoning popularity of the Internet, of course, meant that this behavior had to be modified. Otherwise, it would be easy for a rogue programmer to create a stream of global broadcasts that would propagate to all networks on the Internet, effectively clogging the worldwide system with bogus broadcasts and stopping normal traffic. To eliminate this possibility, routers do not send global IP broadcasts to other networks unless specifically configured to do so (which is practically never). Instead, they silently ignore global broadcasts, effectively turning them into local broadcasts that are seen only on the local network over which they were sent.

Implementing Broadcasting with C#

The .NET network library contains elements for sending and receiving broadcast packets. This section describes the techniques necessary to handle broadcast packets in your network application programs.

Sending Broadcast Packets

By default, sockets are not allowed to send broadcast messages. You can test this by running the simple program shown in Listing 10.1.

Listing 10.1: The BadBroadcast.cs program
Start example
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class BadBroadcast
{
  public static void Main()
  {
   Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                ProtocolType.Udp);
   IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 9050);
   byte[] data = Encoding.ASCII.GetBytes("This is a test message");
   sock.SendTo(data, iep);
   sock.Close();
  }
}
End example

When you try to run this program, you will get an Exception message:

C:\>BadBroadcast
Unhandled Exception: System.Net.Sockets.SocketException: An attempt was made to
access a socket in a way forbidden by its access permissions
  at System.Net.Sockets.Socket.SendTo(Byte[] buffer, Int32 offset, Int32 size,
SocketFlags socketFlags, EndPoint remoteEP)
  at System.Net.Sockets.Socket.SendTo(Byte[] buffer, EndPoint remoteEP)
  at BadBroadcast.Main()
C:\>

The BadBroadcast.cs program seems simple enough, but when it runs, the .NET environment doesn’t allow the SendTo() method to send the message. As seen, if you attempt to send a broadcast message from a default UDP socket, you will get a SocketException error.

For a C# application to send broadcast packets, the broadcast socket option must be set on the created socket using the SetSocketOption() method of the Socket class. (The SetSocketOption was discussed in Chapter 3, "C# Network Programming Classes.") Here is a code snippet for using the SetSocketOption() method in this way:

Socket sock = new Socket(AddressFamily.InterNetwork,
        SocketType.Dgram, ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);

Note that the SocketType must be set to Dgram for broadcast messages. The SocketOptionName.Broadcast option is a Socket level option, so the SocketOptionLevel parameter must be set to Socket.

Because the SetSocketOption() method does not allow boolean values for the data parameter, you must set the value parameter to any non-zero value to represent the true boolean value. Zero represents the false boolean value.

After the socket option is set, you specify a broadcast address and port to use for the broadcast and use the SendTo() method to send a message on that address:

IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 9050);
byte[] data = Encoding.Ascii.GetBytes("test message");
sock.SendTo(data, iep);

Using the Broadcast property of the IPAddress class as a destination address, the program will send the broadcast message out to all network interfaces configured on the device. To limit the broadcast to a specific interface, you must manually supply a local broadcast address to use for the destination address. Listing 10.2 demonstrates using both the IPAddress.Broadcast address and a local broadcast address in a sample C# program, Broadcst.cs.

Listing 10.2: The Broadcst.cs program
Start example
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class Broadcst
{
  public static void Main()
  {
   Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                ProtocolType.Udp);
   IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
   IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 9050);
   string hostname = Dns.GetHostName();
   byte[] data = Encoding.ASCII.GetBytes(hostname);
   sock.SetSocketOption(SocketOptionLevel.Socket,
              SocketOptionName.Broadcast, 1);
   sock.SendTo(data, iep1);
   sock.SendTo(data, iep2);
   sock.Close();
  }
}
End example

The Broadcst program creates two separate IPEndPoint objects, one using the IPAddress.Broadcast address and one using a local broadcast address 192.168.1.255. Next, the local hostname of the device is determined using the standard Dns GetHostName() method, and it is sent out in two separate broadcast messages.

As you’ve done throughout this book, you can use WinDump or Analyzer to monitor the network for the broadcast messages. Figure illustrates the output of the Broadcst program in Analyzer.

Click To expand
Figure: The Analyzer output from the Broadcst program

The Analyzer program captured two separate broadcast packets sent out on the network. The first packet was sent to the 255.255.255.255. global broadcast address, which resulted from setting the destination address to IPAddress.Broadcast. The second broadcast packet was sent to the local 192.168.1.255 address, the manually specified local broadcast address in the program.

Receiving Broadcast Packets

Receiving broadcast packets is a little less complex than sending them. By default, no special options are required for a socket to receive a broadcast message. If a socket is listening on a specified UDP port, it will accept any message destined for either a broadcast address or the local IP address of the device. The RecvBroadcst.cs program in Listing 10.3 demonstrates this by creating a socket to listen for packets on UDP port 9050, the same port from which the Broadcst program is sending broadcast messages.

Listing 10.3: The RecvBroadcst.cs program
Start example
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class RecvBroadcst
{
  public static void Main()
  {
   Socket sock = new Socket(AddressFamily.InterNetwork,
           SocketType.Dgram, ProtocolType.Udp);
   IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
   sock.Bind(iep);
   EndPoint ep = (EndPoint)iep;
   Console.WriteLine("Ready to receive…");
   byte[] data = new byte[1024];
   int recv = sock.ReceiveFrom(data, ref ep);
   string stringData = Encoding.ASCII.GetString(data, 0, recv);
   Console.WriteLine("received: {0} from: {1}",
              stringData, ep.ToString());
   data = new byte[1024];
   recv = sock.ReceiveFrom(data, ref ep);
   stringData = Encoding.ASCII.GetString(data, 0, recv);
   Console.WriteLine("received: {0} from: {1}",
              stringData, ep.ToString());
   sock.Close();
  }
}
End example

The RecvBroadcst program is a simple UDP program that creates a socket and binds it to all network interfaces on the device, using port 9050, the same port that the Broadcst program uses to send its broadcast messages. After binding the socket to the UDP port, the program attempts to receive two messages sent to the port and displays the message and the sending host address information.

You can start the RecvBroadcst program in a command prompt window, and then run the Broadcst program from either another command prompt window on the same device, or from another device on the same subnet. A sample output from the RecvBroadcst program is as follows:

C:\>RecvBroadcst
received: abednego from: 192.168.1.6:1042
received: abednego from: 192.168.1.6:1042
C:\>

As expected, the RecvBroadcst program received both forms of the broadcast message that were sent by the Broadcst program.

Warning 

When testing broadcast programs, remember to use devices on the same subnet.

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows