Compare IP Address if it is lower than the other one

两盒软妹~` 提交于 2019-12-05 16:08:41

You can convert each IP address into an integer and do a comparison that way. If you have access to the Extension Methods functionality of the recent .NET Framework then try the following.

public static class IPExtensions
{
   public static int ToInteger(this IPAddress IP)
   {
      int result = 0;

      byte[] bytes = IP.GetAddressBytes();
      result = (int)(bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3]);

      return result;
   }

   //returns 0 if equal
   //returns 1 if ip1 > ip2
   //returns -1 if ip1 < ip2
   public static int Compare(this IPAddress IP1, IPAddress IP2)
   {
       int ip1 = IP1.ToInteger();
       int ip2 = IP2.ToInteger();
       return (((ip1 - ip2) >> 0x1F) | (int)((uint)(-(ip1 - ip2)) >> 0x1F));
   }
}

class Program
{
    static void Main(string[] args)
    {
        IPAddress ip1 = IPAddress.Parse("127.0.0.1");
        IPAddress ip2 = IPAddress.Parse("10.254.254.254");

        if (ip1.Compare(ip2) == 0)
           Console.WriteLine("ip1 == ip2");
        else if (ip1.Compare(ip2) == 1)
           Console.WriteLine("ip1 > ip2");
        else if (ip1.Compare(ip2) == -1)
           Console.WriteLine("ip1 < ip2");
    }
}

EDIT This does not support IPv6 but can be modified to do so.

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));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!