Anyone know how to compare 2 ipaddress to see if the ipaddress is lower than the other.
i.e
bool b = CurrentIpAddress.IsLowerCompareTo(AnotherIPAddress);
I would also like to support both IPV4 and IPV6.
You can call IPAddress.GetAddressBytes and write a for loop to compare each individual byte.
vane has the right idea but is unfortunately using signed integers. The problem with that is evident in the one comment on his answer. If one of the resulting integers has its most significant bit set, it's interpreted as negative and throws off the comparison.
Here's a modified version (written in Linqpad, so not a complete program) that yields correct results.
public static class IpExtensions
{
public static uint ToUint32(this IPAddress ipAddress)
{
var bytes = ipAddress.GetAddressBytes();
return ((uint)(bytes[0] << 24)) |
((uint)(bytes[1] << 16)) |
((uint)(bytes[2] << 8)) |
((uint)(bytes[3]));
}
}
public static int CompareIpAddresses(IPAddress first, IPAddress second)
{
var int1 = first.ToUint32();
var int2 = second.ToUint32();
if (int1 == int2)
return 0;
if (int1 > int2)
return 1;
return -1;
}
void Main()
{
var ip1 = new IPAddress(new byte[] { 255, 255, 255, 255 });
var ip2 = new IPAddress(new byte[] { 0, 0, 0, 0 });
Console.WriteLine(CompareIpAddresses(ip1, ip2));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With