比较IP地址,如果它低于另一个 [英] Compare IP Address if it is lower than the other one

查看:170
本文介绍了比较IP地址,如果它低于另一个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都知道如何比较2 ipaddress以查看ipaddress是否低于其他ipaddress。

Anyone know how to compare 2 ipaddress to see if the ipaddress is lower than the other.

bool b = CurrentIpAddress.IsLowerCompareTo(AnotherIPAddress);

我也想支持IPV4和IPV6。

I would also like to support both IPV4 and IPV6.

推荐答案

您可以将每个IP地址转换为整数,然后进行比较。如果你可以访问最近的.NET框架的扩展方法功能,然后尝试以下。

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 支持IPv6,但可以修改为这样做。

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

这篇关于比较IP地址,如果它低于另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆