.NET有IP地址范围的概念吗?
我需要测试一个给定的IP地址是否在一组地址范围内。
我可以编写一些API,例如:
IPRange ipRange = IPRange.Parse("127.0.0.1-127.0.0.15");
ipRange.Contains(someAddress);
但是如果已经有类似的功能内置,我就不想重新发明轮子了。
.NET有IP地址范围的概念吗?
我需要测试一个给定的IP地址是否在一组地址范围内。
我可以编写一些API,例如:
IPRange ipRange = IPRange.Parse("127.0.0.1-127.0.0.15");
ipRange.Contains(someAddress);
但是如果已经有类似的功能内置,我就不想重新发明轮子了。
'test values
Dim rangeStart As Net.IPAddress = Net.IPAddress.Parse("192.168.133.1")
Dim rangeEnd As Net.IPAddress = Net.IPAddress.Parse("192.168.133.254")
Dim check As Net.IPAddress = Net.IPAddress.Parse("192.168.133.230")
'get the bytes of the address
Dim rbs() As Byte = rangeStart.GetAddressBytes
Dim rbe() As Byte = rangeEnd.GetAddressBytes
Dim cb() As Byte = check.GetAddressBytes
'reverse them for conversion
Array.Reverse(rbs)
Array.Reverse(rbe)
Array.Reverse(cb)
'convert them
Dim rs As UInt32 = BitConverter.ToUInt32(rbs, 0)
Dim re As UInt32 = BitConverter.ToUInt32(rbe, 0)
Dim chk As UInt32 = BitConverter.ToUInt32(cb, 0)
'check
If chk >= rs AndAlso chk <= re Then
Debug.WriteLine("In Range")
Else
Debug.WriteLine("Not In Range")
End If
这里是关于 dbasnett's answer 的快速翻译,适用于 C#:
public static bool IsIPInRange(string ip, string ipStart, string ipEnd)
{
var pIP = IPAddress.Parse(ip);
var pIPStart = IPAddress.Parse(ipStart);
var pIPEnd = IPAddress.Parse(ipEnd);
var bIP = pIP.GetAddressBytes().Reverse().ToArray();
var bIPStart = pIPStart.GetAddressBytes().Reverse().ToArray();
var bIPEnd = pIPEnd.GetAddressBytes().Reverse().ToArray();
var uIP = BitConverter.ToUInt32(bIP, 0);
var uIPStart = BitConverter.ToUInt32(bIPStart, 0);
var uIPEnd = BitConverter.ToUInt32(bIPEnd, 0);
return uIP >= uIPStart && uIP <= uIPEnd;
}