计算ip是否在c#中的指定范围内?

时间:2014-07-31 13:06:55

标签: sql-server ip

我有一个包含IP和国家/地区的数据库。 我得到用户IP并想知道国家

数据是

from     |to     |country
-------------------------
1.1.1.1.1|2.2.2.2| US
5.5.5.5.5|6.6.6.6| CN

我怎样才能找到ip 5.6.0.0的国家/地区?

2 个答案:

答案 0 :(得分:0)

用“。”分割地址后进行简单检查。从每个分割值开始比较从左到右。

例如:

bool BelongsOrNot(String from, String to, String ip) {
   String []froms = from.Split(".");
   String []tos = to.Split(".");
   String []ips = ip.Split(".");
   for(var i=0;i<ips.length; i++){
      int ipi = Int32.Parse(ips[i]);
      int fromi = Int32.Parse(frons[i]);
      int toi = Inte32.Parse(tos[i]);
      if(toi>ipi && fromi < ipi){
        return false;
      }
   }
   return true;
}

希望这有帮助。

答案 1 :(得分:0)

按如下方式创建新课程IP

public class IP : System.Net.IPAddress, IComparable<IP>
{
    public IP(long newAddress) : base(newAddress)
    {
    }

    public IP(byte[] address, long scopeid) : base(address, scopeid)
    {
    }

    public IP(byte[] address) : base(address)
    {
    }


    public int CompareTo(IP other)
    {
        byte[] ip1 = GetAddressBytes();
        byte[] ip2 = other.GetAddressBytes();
        for (int i = 0; i < ip1.Length; i++)
        {
            if (ip1[i] > ip2[i])
                return 1;
            if (ip1[i] < ip2[i])
                return -1;
        }
        return 0;
    }
}

检查指定的IP是否属于范围:

IP ipRangeLow = new IP(new byte[] { 5, 5, 5, 5 });
IP ipRangeHigh = new IP(new byte[] { 6, 6, 6, 6 });

IP ip = new IP(new byte[] { 5, 6, 0, 0 });
bool ipInRange = ip.CompareTo(ipRangeLow) >= 0 && ip.CompareTo(ipRangeHigh) <= 0;
相关问题