Determining IPv4 Broadcast Address in C#

When dealing with IPv4 network, one thing that everybody needs sooner or later is a broadcast address based on IP address and its netmask.

Let's take well known address/netmask combo as an example - In binary this would be:

Address .: 11000000 10101000 00000001 00000001
Mask ....: 11111111 11111111 11111111 00000000
Broadcast: 11000000 10101000 00000001 11111111

To get its broadcast address, we simply copy all address bits where netmask is set. All remaining bits are set and our broadcast address is found.

A bit more complicated example would be address with a netmask

Address .: 00001010 00100001 00101100 00010110
Mask ....: 11111111 11111111 11111111 11111100
Broadcast: 00001010 00100001 00101100 00010111

But principle is the same, for broadcast address we copy all address bits where mask is 1. Whatever remains gets a value of 1. In this case this results in

As you can see above, everything we need is simply taking an original address and performing OR operation between it and a negative netmask: broadcast = address | ~mask. In C# these steps are easiest to achieve if we convert everything to integers first:

var addressInt = BitConverter.ToInt32(address.GetAddressBytes(), 0);
var maskInt = BitConverter.ToInt32(mask.GetAddressBytes(), 0);
var broadcastInt = addressInt | ~maskInt;
var broadcast = new IPAddress(BitConverter.GetBytes(broadcastInt));

Full example is available for download.

2 thoughts to “Determining IPv4 Broadcast Address in C#”

    1. Yes and no. IPAddress.Broadcast will work if you get it from the network interface. However, if you have a custom entry field, that won’t work. This procedure works even if IPAddress carries no subnet information.

Leave a Reply

Your email address will not be published. Required fields are marked *