开发者

Testing if an IP address is within a range of addresses with .NET

开发者 https://www.devze.com 2023-03-19 02:20 出处:网络
Does .NET have the notion of IP Address Ranges? I need to test if a given IP address is within a range of addresses.

Does .NET have the notion of IP Address Ranges?

I need to test if a given IP address is within a range of addresses.

I could write some API that would give me something like

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

but I don't开发者_如何学Python want to reinvent the wheel if there is already similar functionality built in.


No, but here is how it can be done (VB since code tag not included in 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


Here just a quick translation of dbasnett's answer to 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;
}

Here is a full working .NET Fiddle with an example.

Hope this doesn't count as an off-topic answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消