views:

1228

answers:

2

I have a subnet in the format 10.132.0.0/20 and an IP address from the ASP.Net request object.

Is there a .NET framework function to check to see if the IP address is within the given subnet?

If not, how can it be done? Bit manipulation, I guess?

+3  A: 

Bit manipulation works. Stuff the IP into a 32-bits unsigned integer, do the same with the subnet's address, &-mask both with 0xFFFFFFFF << (32-20) and compare:

unsigned int net = ..., ip = ...;
int network_bits = 20;
unsigned int mask = 0xFFFFFFFF << (32 - network_bits);
if ((net & mask) == (ip & mask)) {
  // ...
}
Thomas
Or, if as common, the subnet is given as a number like 255.255.240.0, just stuff the mask into a 32-bit integer instead of the shift.
erikkallen
I found the System.Net.IPAddress class helpful for parsing and decomposing IP addresses into bytes
Ryan Michela
+3  A: 

Take a look at this post on MSDN blogs. It contains an extension method (IsInSameSubnet) that should meet your needs as well as some other goodies.

Chris Shouts