一尘不染

如何检查输入的IP是否在特定IP范围内

c#

如果我们让用户输入几个IP范围,例如172.16.11.5-100,我该如何编写一个函数来检查IP(172.16.11.50)是否在该范围内?

.NET中是否有任何现有库可利用?


阅读 389

收藏
2020-05-19

共1个答案

一尘不染

框架中没有内置任何东西,但是创建一个IPAddressRange类不需要花费很多精力。

您可以通过在较低地址,较高地址和比较地址上调用IPAddress.GetAddressBytes来比较范围。从第一个字节开始,检查比较地址是否在高/低地址范围内。

此方法适用于IPv4和IPv6地址。

public class IPAddressRange
{
    readonly AddressFamily addressFamily;
    readonly byte[] lowerBytes;
    readonly byte[] upperBytes;

    public IPAddressRange(IPAddress lowerInclusive, IPAddress upperInclusive)
    {
        // Assert that lower.AddressFamily == upper.AddressFamily

        this.addressFamily = lowerInclusive.AddressFamily;
        this.lowerBytes = lowerInclusive.GetAddressBytes();
        this.upperBytes = upperInclusive.GetAddressBytes();
    }

    public bool IsInRange(IPAddress address)
    {
        if (address.AddressFamily != addressFamily)
        {
            return false;
        }

        byte[] addressBytes = address.GetAddressBytes();

        bool lowerBoundary = true, upperBoundary = true;

        for (int i = 0; i < this.lowerBytes.Length && 
            (lowerBoundary || upperBoundary); i++)
        {
            if ((lowerBoundary && addressBytes[i] < lowerBytes[i]) ||
                (upperBoundary && addressBytes[i] > upperBytes[i]))
            {
                return false;
            }

            lowerBoundary &= (addressBytes[i] == lowerBytes[i]);
            upperBoundary &= (addressBytes[i] == upperBytes[i]);
        }

        return true;
    }
}

注意:以上代码可以扩展为添加公共静态工厂方法 FromCidr(IPAddress address, int bits)

2020-05-19