【问题标题】:Ip Range control on c# [duplicate]c#上的IP范围控制[重复]
【发布时间】:2013-07-29 03:30:48
【问题描述】:

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

从:127.0.0.1 到:127.0.0.255 等

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

【问题讨论】:

  • 您的 IP 地址范围是否必须存储为“发件人”和“收件人”?您是否能够将其存储为网络地址,例如127.0.0.0/24?这有助于更好地进行范围检查。

标签: c# ip


【解决方案1】:

Convert the IPs to an integer,检查是否在范围内。

  • 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!
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 2019-07-04
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    • 2011-09-05
    相关资源
    最近更新 更多