如何在C#中比较IP地址范围?

时间:2012-05-09 23:25:36

标签: c# ipv6 ipv4 cidr

如果我有一个IP地址范围(CIDR表示法),我需要知道某个任意IP地址是否在该范围内 - 两者都表示为字符串 - 用C#执行此操作的最简单方法是什么?

示例:

  • IPv4范围:192.168.168.100/24,要检查的IP:192.168.168.200
  • IPv6范围:fe80::202:b3ff:fe1e:8329/24,要检查的IP:2001:db8::

3 个答案:

答案 0 :(得分:11)

这是一个简单的课程:

public class IPSubnet
{
    private readonly byte[] _address;
    private readonly int _prefixLength;

    public IPSubnet(string value)
    {
        if (value == null)
            throw new ArgumentNullException("value");

        string[] parts = value.Split('/');
        if (parts.Length != 2)
            throw new ArgumentException("Invalid CIDR notation.", "value");

        _address = IPAddress.Parse(parts[0]).GetAddressBytes();
        _prefixLength = Convert.ToInt32(parts[1], 10);
    }

    public bool Contains(string address)
    {
        return this.Contains(IPAddress.Parse(address).GetAddressBytes());
    }

    public bool Contains(byte[] address)
    {
        if (address == null)
            throw new ArgumentNullException("address");

        if (address.Length != _address.Length)
            return false; // IPv4/IPv6 mismatch

        int index = 0;
        int bits = _prefixLength;

        for (; bits >= 8; bits -= 8)
        {
            if (address[index] != _address[index])
                return false;
            ++index;
        }

        if (bits > 0)
        {
            int mask = (byte)~(255 >> bits);
            if ((address[index] & mask) != (_address[index] & mask))
                return false;
        }

        return true;
    }
}

样本用法:

Console.WriteLine(new IPSubnet("192.168.168.100/24").Contains("192.168.168.200")); // True
Console.WriteLine(new IPSubnet("fe80::202:b3ff:fe1e:8329/24").Contains("2001:db8::")); // False

此类将所有IPv4地址视为与所有IPv6地址不同,不会尝试在IPv4和IPv6之间进行转换。

答案 1 :(得分:2)

答案 2 :(得分:1)

我建议使用IPNetwork Library https://github.com/lduchosal/ipnetwork。 从版本2开始,它也支持IPv4和IPv6。

<强>的IPv6

  IPNetwork ipnetwork = IPNetwork.Parse("fe80::202:b3ff:fe1e:8329/24");

  IPAddress ipaddress = IPAddress.Parse("2001:db8::");
  IPAddress ipaddress2 = IPAddress.Parse("fe80::202:b3ff:fe1e:1");

  bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress);
  bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2);

  Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress,     contains1);
  Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2,     contains2);

输出

   fe80::/24 contains 2001:db8:: : False
   fe80::/24 contains fe80::202:b3ff:fe1e:1 : True

<强>的IPv4

  IPNetwork ipnetwork = IPNetwork.Parse("192.168.168.100/24");

  IPAddress ipaddress = IPAddress.Parse("192.168.168.200");
  IPAddress ipaddress2 = IPAddress.Parse("192.168.0.200");

  bool contains1 = IPNetwork.Contains(ipnetwork, ipaddress);
  bool contains2 = IPNetwork.Contains(ipnetwork, ipaddress2);

  Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress, contains1);
  Console.WriteLine("{0} contains {1} : {2}", ipnetwork, ipaddress2, contains2);

输出

  192.168.168.0/24 contains 192.168.168.200 : True
  192.168.168.0/24 contains 192.168.0.200 : False

玩得开心!