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 i
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:
using System.Net; // Used to access IPAddress
bool IsAddressOnSubnet(string address, string subnet, string mask)
{
try
{
IPAddress Address = IPAddress.Parse(address);
IPAddress Subnet = IPAddress.Parse(subnet);
IPAddress Mask = IPAddress.Parse(mask);
Byte[] addressOctets = Address.GetAddressBytes();
Byte[] subnetOctets = Mask.GetAddressBytes();
Byte[] networkOctets = Subnet.GetAddressBytes();
return
((networkOctets[0] & subnetOctets[0]) == (addressOctets[0] & subnetOctets[0])) &&
((networkOctets[1] & subnetOctets[1]) == (addressOctets[1] & subnetOctets[1])) &&
((networkOctets[2] & subnetOctets[2]) == (addressOctets[2] & subnetOctets[2])) &&
((networkOctets[3] & subnetOctets[3]) == (addressOctets[3] & subnetOctets[3]));
}
catch (System.Exception ex)
{
return false;
}
}
Special thanks to Reference