Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare IP Address if it is lower than the other one

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.

like image 468
reggieboyYEAH Avatar asked Nov 29 '12 17:11

reggieboyYEAH


2 Answers

You can call IPAddress.GetAddressBytes and write a for loop to compare each individual byte.

like image 69
Matthew Avatar answered Oct 16 '22 06:10

Matthew


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));
}
like image 3
Brandon Hood Avatar answered Oct 16 '22 07:10

Brandon Hood