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?
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?
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)) {
// ...
}
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.