views:

372

answers:

1

Given a IPv4 address in the form of a string (ex. "10.171.24.69") and a netmask (ex. "255.255.255.128" or "25" for number of bits in network part) I need to compute the broadcast address, which may be by either zeroing or one-ing the bits in the host part (depending on the IPUseZeroBroadcast property which I can query via WMI).

I'm examining the System.Net.IPAddress class but it looks insufficient to the task. Any suggestions?

+2  A: 

I don't know of any built in, functions, but you could calculate it yourself easily enough

static IPAddress ComputeBroadcastIP(IPAddress ip, IPAddress netmask)
{
    byte[] ipBytes = ip.GetAddressBytes();
    byte[] maskBytes = netmask.GetAddressBytes();
    byte[] broadcastBytes = new byte[ipBytes.Length];

    for (int i = 0; i < broadcastBytes.Length; i++)
    {
        broadcastBytes[i] = (byte)(ipBytes[i] | ~maskBytes[i]);
    }

    return new IPAddress(broadcastBytes);
}

You could also do

IPAddress broadcast = new IPAddress((ip.Address | (~mask.Address)) & 0xffffffff);

but the .Address property is deprecated.

Note that to convert a string like "1.2.3.4" to an IPAddress, you can call IPAddress.Parse, e.g.

IPAddress foo = IPAddress.Parse("1.2.3.4");
Daniel LeCheminant