Comparison of IPAddresses

  • Thread starter Thread starter Noël Danjou
  • Start date Start date
N

Noël Danjou

Hello,

I'd like to verify if an IP address (as an IPAddress parameter) is in a
range defined by two other IP addresses (also passed as IPAddress
parameters), something like IsLoopback() but not only for 127.x.y.z and not
only for x,y,z in the 0-255 range.

There is an Equals member function but it only compares if two IP addresses
are equal which is not enough in my case what I'd need is a Compare()
function which returns <0, 0 or >0 like String.Compare().

Currently I target IPv4 but I'd like it to be compatible with IPv6 too if
the IPAddress and the range are IPv6. In the Framework V1.0 I was using the
Address property like below, but in the V1.1 it is marked as obsolete.

Here is what I was doing:

public static bool IsAddressInRange(IPAddress addrSrc, IPAddressRange range)
{
long addr = IPAddress.NetworkToHostOrder(addrSrc.Address);
return (addr >= IPAddress.NetworkToHostOrder(range.lo.Address) &&
addr <= IPAddress.NetworkToHostOrder(range.hi.Address));
}

Could you recommend a method to do that for both address families? Thank
you.
 
Hi,

I have written a function that will do the similar work to calling the
Address property. So you may use it instead of using Addess property to
avoid the "obsolete" message.

public static bool IsAddressInRange(IPAddress addrSrc, IPAddressRange range)
{
//long addr = IPAddress.NetworkToHostOrder(addrSrc.Address);
//return (addr >= IPAddress.NetworkToHostOrder(range.lo.Address) &&
//addr <= IPAddress.NetworkToHostOrder(range.hi.Address));

long addr = IPAddress.NetworkToHostOrder(getLongFromAddress(addrSrc));
return (addr >= IPAddress.NetworkToHostOrder(getLongFromAddress(range.lo))
&&
addr <= IPAddress.NetworkToHostOrder(getLongFromAddress(range.hi)));
}

private static long getLongFromAddress (IPAddress ipa)
{
byte[] b = ipa.GetAddressBytes();
long l = 0;
for (int i = 0; i < b.Length ; i++)
{
l += (long) (b * Math.Pow(256,i));
}
return l;
}

public struct IPAddressRange
{
public IPAddress hi;
public IPAddress lo;
}

Have a look and see whether it works for you.

If you have any concerns, please feel free to let me know.

Felix Wang
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
Hi Felix,

Thank you very much for your replies and your sample code. I tried your last
sample with sucess so I will use it. I just added an AddressFamily test at
the beginning to avoid a possible out-of-range index in case the
AddressFamily of the address and the range differs.

Thanks again for your help.
 
Back
Top