Greg B
Greg B

Reputation: 14888

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

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 want to reinvent the wheel if there is already similar functionality built in.

Upvotes: 4

Views: 4652

Answers (2)

Uwe Keim
Uwe Keim

Reputation: 40736

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.

Upvotes: 0

dbasnett
dbasnett

Reputation: 11773

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

Upvotes: 5

Related Questions