I have a subnet in the format 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)) {
  // ...
Or, if as common, the subnet is given as a number like, just stuff the mask into a 32-bit integer instead of the shift.
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