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

后端 未结 7 1452
深忆病人
深忆病人 2020-12-01 12:15

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

7条回答
  •  情话喂你
    2020-12-01 12:21

    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

提交回复
热议问题