4

我有一个由“从”和“到”组成的 IP 范围

从:127.0.0.1 到:127.0.0.255 等。

如何控制发送的 IP 为 127.0.1.253?是否在IP范围内?

4

1 回答 1

8

将 IP 转换为整数,并检查它是否在范围内。

  • 127.0.0.1 = 2130706433
  • 127.0.0.255 = 2130706687

  • 127.0.1.253 = 2130706941

因此,它不适合该范围。


 public static long IP2Long(string ip)
   {
       string[] ipBytes;
       double num = 0;
       if(!string.IsNullOrEmpty(ip))
       {
           ipBytes = ip.Split('.');
           for (int i = ipBytes.Length - 1; i >= 0; i--)
           {
               num += ((int.Parse(ipBytes[i]) % 256) * Math.Pow(256, (3 - i)));
           }
       }
       return (long)num;
   }

资料来源: http: //geekswithblogs.net/rgupta/archive/2009/04/29/convert-ip-to-long-and-vice-versa-c.aspx


因此,使用此方法您可以执行以下操作:

long start = IP2Long("127.0.0.1");
long end = IP2Long("127.0.0.255");
long ipAddress = IP2Long("127.0.1.253");

bool inRange = (ipAddress >= start && ipAddress <= end);

if (inRange){
  //IP Address fits within range!
}
于 2013-07-29T11:07:59.987 回答