Calculating the broadcast address for a subnet





1.00/5 (2 votes)
How to calculate the broadcast address for a subnet.
Introduction
This code returns the subnet broadcast address for a given IP address and subnet mask.
I needed it for a WOL function on a website which was in a different subnet and where the standard broadcast address didn't work.
Using the code
This function is quite easy, and could be used, for example, in an UdpClient
object, like this:
UdpClient client = new UdpClient();
client.Connect(CalculateBroadCastAddress(ip,nm).ToString(), 40000);
Here is the complete source code:
using System.Net.Sockets;
using System.Net;
using System.Globalization;
using System.Collections;
static IPAddress CalculateBroadCastAddress(IPAddress currentIP, IPAddress ipNetMask)
{
string[] strCurrentIP = currentIP.ToString().Split('.');
string[] strIPNetMask = ipNetMask.ToString().Split('.');
ArrayList arBroadCast = new ArrayList();
for (int i = 0; i < 4; i++)
{
int nrBCOct = int.Parse(strCurrentIP[i]) | (int.Parse(strIPNetMask[i]) ^ 255);
arBroadCast.Add(nrBCOct.ToString());
}
return IPAddress.Parse(arBroadCast[0] + "." + arBroadCast[1] +
"." + arBroadCast[2] + "." + arBroadCast[3]);
}