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

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

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

回答:

框架中没有内置任何东西,但是创建一个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)

以上是 如何检查输入的IP是否在特定IP范围内 的全部内容, 来源链接: utcz.com/qa/407016.html

回到顶部