Functions to manipulate IPv4 addresses in C#?
-
21-08-2019 - |
Question
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?
Solution
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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow