问题描述
如果我们让用户输入几个 ip 范围,例如 172.16.11.5 - 100,我如何编写一个函数来检查 IP (172.16.11.50) 是否在这些范围内?
If we let users input a couple of ip ranges, e.g., 172.16.11.5 - 100, how could I write a function to check if a IP (172.16.11.50) falls in the ranges?
.NET 中是否有任何现有的库可供利用?
Is there any existing library in .NET to leverage?
推荐答案
框架中没有内置任何东西,但是创建一个 IPAddressRange
类并不需要太多努力.
There's nothing built into the framework, but it wouldn't take much effort to create an IPAddressRange
class.
您可以通过调用 IPAddress.GetAddressBytes 关于低位地址、高位地址和比较地址.从第一个字节开始,检查比较地址是否在高/低地址范围内.
You'd compare the ranges by calling IPAddress.GetAddressBytes on the lower address, upper address and comparison address. Starting at the first byte, check if the comparison address is in the range of the upper/lower address.
此方法适用于 IPv4 和 IPv6 地址.
This method works for both IPv4 and IPv6 addresses.
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;
}
}
NB:上面的代码可以扩展添加公共静态工厂方法FromCidr(IPAddress address, int bits)
NB: The above code could be extended to add public static factory methods FromCidr(IPAddress address, int bits)
这篇关于如何检查输入 IP 是否属于特定 IP 范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!