Fastest way to Check if an IP is in a given range?

  • Thread starter Thread starter Russ Ryba
  • Start date Start date
R

Russ Ryba

Hi,

I'm wondering what the fastest way to Check if an IP is in a given range?

Right now I convert the address to a string (192.168.X.X type) and then
parse the string to see if a given string is in the range. I know with
the data conversion I'm doing I must be going quite slow.

Is there a way to check using just the System.Net.IPAddress found in an
AddressList without converting to string?

Thanks,
- Russ
 
Each octet is a byte, so you can simply do a numerical comparison on them.
Check byte[2] then byte[3].

-Chris
 
If you are checking against netmask, you can use
IPAddress addr;

if ( (addr.Address & mask) != 0 )
{
// do something
}

if you need to compare agains a range that cannot be representedby a mask,
then just compare the 1st octet:

int lastOctet = IPAddress.NetworkToHostOrder(addr.Address) & 0xff;
Dim lastOctet as Integer = IPAddress.NetworkToHostOrder(addr.Address) And
&HFF
 
Hey,

I just try to do the same...
I think you schould convert the IP-Range into two Long and then you can
check if the IP is between the two values.

What I'm searching for is an easy way to get out of an IP and the
subnetmask the range of the possible IPs like:
192.168.0.1 Subnet 255.255.240.0

Chris



Public Function IP2Long(ByVal DottedIP As String) As Object
Dim arr = Split(DottedIP, ".")
If UBound(arr) = 3 Then
For i As Byte = 1 To 4
If arr(i - 1) > 255 Or arr(i - 1) < 0 Then Return 0
IP2Long = ((arr(i - 1) Mod 256) * (256 ^ (4 - i))) + IP2Long
Next
End If
End Function
 
Back
Top