Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an IP address is within a particular subnet

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?

like image 774
Ryan Michela Avatar asked Sep 30 '09 16:09

Ryan Michela


People also ask

How do you determine if an IP address is in a subnet?

To determine the first usable IP address within a subnet, the first bit from the right must be 1. To determine the last usable IP address within a subnet all of the host bits except the first bit from the right should all be 1s. The broadcast IP of any subnet is when all of the host bits are 1s.

Is IP within subnet?

A subnet is a division of an IP network (internet protocol suite), where an IP network is a set of communications protocols used on the Internet and other similar networks.


1 Answers

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.

public static class IPAddressExtensions {     public static IPAddress GetBroadcastAddress(this IPAddress address, IPAddress subnetMask)     {         byte[] ipAdressBytes = address.GetAddressBytes();         byte[] subnetMaskBytes = subnetMask.GetAddressBytes();          if (ipAdressBytes.Length != subnetMaskBytes.Length)             throw new ArgumentException("Lengths of IP address and subnet mask do not match.");          byte[] broadcastAddress = new byte[ipAdressBytes.Length];         for (int i = 0; i < broadcastAddress.Length; i++)         {             broadcastAddress[i] = (byte)(ipAdressBytes[i] | (subnetMaskBytes[i] ^ 255));         }         return new IPAddress(broadcastAddress);     }      public static IPAddress GetNetworkAddress(this IPAddress address, IPAddress subnetMask)     {         byte[] ipAdressBytes = address.GetAddressBytes();         byte[] subnetMaskBytes = subnetMask.GetAddressBytes();          if (ipAdressBytes.Length != subnetMaskBytes.Length)             throw new ArgumentException("Lengths of IP address and subnet mask do not match.");          byte[] broadcastAddress = new byte[ipAdressBytes.Length];         for (int i = 0; i < broadcastAddress.Length; i++)         {             broadcastAddress[i] = (byte)(ipAdressBytes[i] & (subnetMaskBytes[i]));         }         return new IPAddress(broadcastAddress);     }      public static bool IsInSameSubnet(this IPAddress address2, IPAddress address, IPAddress subnetMask)     {         IPAddress network1 = address.GetNetworkAddress(subnetMask);         IPAddress network2 = address2.GetNetworkAddress(subnetMask);          return network1.Equals(network2);     } } 
like image 120
Chris Shouts Avatar answered Oct 08 '22 18:10

Chris Shouts