If I have a subnet mask e.g. 255.255.255.0
and an ip address 192.168.1.5
, is there an easy way to determine all the possible ip addresses within th
Good call. Don't use extra libraries for that. It's quite simple. This is how I do it:
public static uint[] GetIpRange(string ip, IPAddress subnet)
{
uint ip2 = Utils.IPv4ToUInt(ip);
uint sub = Utils.IPv4ToUInt(subnet);
uint first = ip2 & sub;
uint last = first | (0xffffffff & ~sub);
return new uint[] { first, last };
}
Note:
You'll need to do some more work converting IPs to uint and back (should be easy enough). Then you can iterate all IPs with a simple for-loop between first and last.
Something like this (not tested):
byte[] bytes = subnet.GetAddressBytes();
uint sub = (uint)((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]);
IPAddress ip1 = IPAddress.Parse(ip);
bytes = ip1.GetAddressBytes();
uint ip2 = (uint)((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]);