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 with0xFFFFFFFF << (32-20)
and compare:I'm late to the party here, but had a similar need, and put together a quick package to do exactly this.
https://www.nuget.org/packages/IpMatcher/
and source:
https://github.com/jchristn/IpMatcher
Simple use:
Since the MSDN blog code relies on a broadcast and IPv6 doesn't have one, I don't know if it works with IPv6.
I ended up with these methods (thanks to nu everest). You can get the subnet and mask from a CIDR notation ("1.2.3.4/5") and check whether an adress is within this network or not.
This works for IPv4 and IPv6:
Example usage:
The solution is to convert the IP Address into bytes using
System.Net.IPAddress
and perform bitwise comparisons on the address, subnet, and mask octets.The Binary AND Operator
&
copies a bit to the result if it exists in both operands.The code:
Special Thanks to Спасибо! Прекрасное решение! Reference
Take a look at IP Address Calculations with C# on MSDN blogs. It contains an extension method (
IsInSameSubnet
) that should meet your needs as well as some other goodies.