测试IP地址是否在.NET的地址范围内

时间:2011-07-07 14:01:08

标签: .net ip-address

.NET是否具有IP地址范围的概念?

我需要测试给定的IP地址是否在地址范围内。

我可以编写一些API,它会给我一些类似

的内容
IPRange ipRange = IPRange.Parse("127.0.0.1-127.0.0.15");
ipRange.Contains(someAddress);

但如果已经内置了类似的功能,我不想重新发明轮子。

2 个答案:

答案 0 :(得分:4)

不,但这是如何做到的(VB因为代码标签不包含在OP中)

'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

答案 1 :(得分:0)

这里只是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;
}

以下是full working .NET Fiddle的示例。

希望这不算作一个偏离主题的答案。