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 – 192.168.1.1/255.255.255.0. 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 192.168.1.255 is found.
A bit more complicated example would be address 10.33.44.22 with a netmask 255.255.255.252:
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 10.33.44.23.
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.