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

Viewed 64640

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?

8 Answers

Using the answers from Thomas and Chris together with Ciscos Subnetting Examples I finally got something to work for IPv4 and IPv6 if you use the CIDR notation (IPAddress/PrefixLength). My IPv6-Implementation might be a bit too straight forward but as there is no UInt128-datatype I couldn't adapt Thomas's solution. Here is the code that seems to work well:

public static bool IsInSubnet(this IPAddress address, string subnetMask)
{
    var slashIdx = subnetMask.IndexOf("/");
    if (slashIdx == -1)
    { // We only handle netmasks in format "IP/PrefixLength".
        throw new NotSupportedException("Only SubNetMasks with a given prefix length are supported.");
    }

    // First parse the address of the netmask before the prefix length.
    var maskAddress = IPAddress.Parse(subnetMask.Substring(0, slashIdx));

    if (maskAddress.AddressFamily != address.AddressFamily)
    { // We got something like an IPV4-Address for an IPv6-Mask. This is not valid.
        return false;
    }

    // Now find out how long the prefix is.
    int maskLength = int.Parse(subnetMask.Substring(slashIdx + 1));

    if (maskLength == 0)
    {
        return true;
    }

    if (maskLength < 0)
    {
        throw new NotSupportedException("A Subnetmask should not be less than 0.");
    }

    if (maskAddress.AddressFamily == AddressFamily.InterNetwork)
    {
        // Convert the mask address to an unsigned integer.
        var maskAddressBits = BitConverter.ToUInt32(maskAddress.GetAddressBytes().Reverse().ToArray(), 0);

        // And convert the IpAddress to an unsigned integer.
        var ipAddressBits = BitConverter.ToUInt32(address.GetAddressBytes().Reverse().ToArray(), 0);

        // Get the mask/network address as unsigned integer.
        uint mask = uint.MaxValue << (32 - maskLength);

        // https://stackoverflow.com/a/1499284/3085985
        // Bitwise AND mask and MaskAddress, this should be the same as mask and IpAddress
        // as the end of the mask is 0000 which leads to both addresses to end with 0000
        // and to start with the prefix.
        return (maskAddressBits & mask) == (ipAddressBits & mask);
    }

    if (maskAddress.AddressFamily == AddressFamily.InterNetworkV6)
    {
        // Convert the mask address to a BitArray. Reverse the BitArray to compare the bits of each byte in the right order.
        var maskAddressBits = new BitArray(maskAddress.GetAddressBytes().Reverse().ToArray());

        // And convert the IpAddress to a BitArray. Reverse the BitArray to compare the bits of each byte in the right order.
        var ipAddressBits = new BitArray(address.GetAddressBytes().Reverse().ToArray());
        var ipAddressLength = ipAddressBits.Length;

        if (maskAddressBits.Length != ipAddressBits.Length)
        {
            throw new ArgumentException("Length of IP Address and Subnet Mask do not match.");
        }

        // Compare the prefix bits.
        for (var i = ipAddressLength - 1; i >= ipAddressLength - maskLength; i--)
        {
            if (ipAddressBits[i] != maskAddressBits[i])
            {
                return false;
            }
        }

        return true;
    }

    throw new NotSupportedException("Only InterNetworkV6 or InterNetwork address families are supported.");
}

And this are the XUnit tests I tested it with:

public class IpAddressExtensionsTests
{
    [Theory]
    [InlineData("192.168.5.85/24", "192.168.5.1")]
    [InlineData("192.168.5.85/24", "192.168.5.254")]
    [InlineData("10.128.240.50/30", "10.128.240.48")]
    [InlineData("10.128.240.50/30", "10.128.240.49")]
    [InlineData("10.128.240.50/30", "10.128.240.50")]
    [InlineData("10.128.240.50/30", "10.128.240.51")]
    [InlineData("192.168.5.85/0", "0.0.0.0")]
    [InlineData("192.168.5.85/0", "255.255.255.255")]
    public void IpV4SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress)
    {
        var ipAddressObj = IPAddress.Parse(ipAddress);
        Assert.True(ipAddressObj.IsInSubnet(netMask));
    }

    [Theory]
    [InlineData("192.168.5.85/24", "192.168.4.254")]
    [InlineData("192.168.5.85/24", "191.168.5.254")]
    [InlineData("10.128.240.50/30", "10.128.240.47")]
    [InlineData("10.128.240.50/30", "10.128.240.52")]
    [InlineData("10.128.240.50/30", "10.128.239.50")]
    [InlineData("10.128.240.50/30", "10.127.240.51")]
    public void IpV4SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress)
    {
        var ipAddressObj = IPAddress.Parse(ipAddress);
        Assert.False(ipAddressObj.IsInSubnet(netMask));
    }

    [Theory]
    [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")]
    [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFFF")]
    [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:0001:0000:0000:0000")]
    [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0012:FFFF:FFFF:FFFF:FFF0")]
    [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0000")]
    [InlineData("2001:db8:abcd:5678::0/53", "2001:0db8:abcd:5000:0000:0000:0000:0000")]
    [InlineData("2001:db8:abcd:5678::0/53", "2001:0db8:abcd:57ff:ffff:ffff:ffff:ffff")]
    [InlineData("2001:db8:abcd:0012::0/0", "::")]
    [InlineData("2001:db8:abcd:0012::0/0", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")]
    public void IpV6SubnetMaskMatchesValidIpAddress(string netMask, string ipAddress)
    {
        var ipAddressObj = IPAddress.Parse(ipAddress);
        Assert.True(ipAddressObj.IsInSubnet(netMask));
    }

    [Theory]
    [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFFF")]
    [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0000:0000:0000:0000")]
    [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0013:0001:0000:0000:0000")]
    [InlineData("2001:db8:abcd:0012::0/64", "2001:0DB8:ABCD:0011:FFFF:FFFF:FFFF:FFF0")]
    [InlineData("2001:db8:abcd:0012::0/128", "2001:0DB8:ABCD:0012:0000:0000:0000:0001")]
    [InlineData("2001:db8:abcd:5678::0/53", "2001:0db8:abcd:4999:0000:0000:0000:0000")]
    [InlineData("2001:db8:abcd:5678::0/53", "2001:0db8:abcd:5800:0000:0000:0000:0000")]
    public void IpV6SubnetMaskDoesNotMatchInvalidIpAddress(string netMask, string ipAddress)
    {
        var ipAddressObj = IPAddress.Parse(ipAddress);
        Assert.False(ipAddressObj.IsInSubnet(netMask));
    }
}

As base for the tests I used Ciscos Subnetting Examples and IBMs IPV6 address examples.

I hope someone finds this helpful ;)

If you are working with ASP.NET Core there is a new class IPNetwork which can be used to test if a IP Address is in a specific network.

I have also created a class which calculates the network and broadcast address and checks if the IP is neither broadcast nor network address.

private static IPValidationFailedReason PerformIPRangeValidation(string ipAddress, string subnetMask)
        {
            IPValidationFailedReason ipValidationType = IPValidationFailedReason.None;
            string networkaddress = string.Empty;
            string broadcastAddress = string.Empty;
            string networkAddressBinary = string.Empty;
            string broadcastAddressBinary = string.Empty;
            int zerosCountInSubnetMask = 0;

            Array.ForEach(subnetMask.Split(SplitterChar), (eachOctet) => Array.ForEach(IPInterfaceHelper.GetOctetWithPadding(eachOctet).Where(c => c == CharZero).ToArray(), (k) => zerosCountInSubnetMask++));

            if (zerosCountInSubnetMask == 0)
            {
                return ipValidationType;
            }

            string ipAddressBinary = IPInterfaceHelper.ToBinary(ipAddress);
            networkAddressBinary = GetNetworkAddressInBinaryFormat(zerosCountInSubnetMask, ipAddressBinary);
            broadcastAddressBinary = GetBroadcastAddressInBinaryFormat(zerosCountInSubnetMask, ipAddressBinary);

            networkaddress = ToIPFromBinary(networkAddressBinary);
            broadcastAddress = ToIPFromBinary(broadcastAddressBinary);

            if (ipAddress == networkaddress)
            {
                ipValidationType = IPValidationFailedReason.NetworkAddressZero;
                return ipValidationType;
            }
            if (ipAddress == broadcastAddress)
            {
                ipValidationType = IPValidationFailedReason.BroadcastAddressNotPermiited;
                return ipValidationType;
            }

            return ipValidationType;
        }


private static string GetNetworkAddressInBinaryFormat(int zeroCountInSubnetMask, string ipAddressBinary)
    {
        string networkAddressBinary = string.Empty;
        int countOfOnesInSubnetMask = TotalBitCount - zeroCountInSubnetMask;
        StringBuilder sb = new StringBuilder(ipAddressBinary);
        //When Subnet is like 255.255.255.0
        if (zeroCountInSubnetMask >= 1 && zeroCountInSubnetMask <= 8)
        {
            networkAddressBinary = sb.Replace(CharOne, CharZero, countOfOnesInSubnetMask + 3, zeroCountInSubnetMask).ToString();
        }
        //When Subnet is like 255.255.0.0
        if (zeroCountInSubnetMask > 8 && zeroCountInSubnetMask <= 16)
        {
            networkAddressBinary = sb.Replace(CharOne, CharZero, countOfOnesInSubnetMask + 2, zeroCountInSubnetMask + 1).ToString();
        }
        //When Subnet is like 255.0.0.0
        if (zeroCountInSubnetMask > 16 && zeroCountInSubnetMask <= 24)
        {
            networkAddressBinary = sb.Replace(CharOne, CharZero, countOfOnesInSubnetMask + 1, zeroCountInSubnetMask + 2).ToString();
        }
        //When Subnet is like 128.0.0.0
        if (zeroCountInSubnetMask > 24 && zeroCountInSubnetMask < 32)
        {
            networkAddressBinary = sb.Replace(CharOne, CharZero, countOfOnesInSubnetMask , zeroCountInSubnetMask + 3).ToString();
        }
        return networkAddressBinary;
    }


 private static string GetBroadcastAddressInBinaryFormat(int zeroCountInSubnetMask, string ipAddressBinary)
    {
        string broadcastAddressBinary = string.Empty;
        int countOfOnesInSubnetMask = TotalBitCount - zeroCountInSubnetMask;
        StringBuilder sb = new StringBuilder(ipAddressBinary);
        //When Subnet is like 255.255.255.0
        if (zeroCountInSubnetMask >= 1 && zeroCountInSubnetMask <= 8)
        {
            broadcastAddressBinary = sb.Replace(CharZero, CharOne, countOfOnesInSubnetMask + 3, zeroCountInSubnetMask).ToString();
        }
        //When Subnet is like 255.255.0.0
        if (zeroCountInSubnetMask > 8 && zeroCountInSubnetMask <= 16)
        {
            broadcastAddressBinary = sb.Replace(CharZero, CharOne, countOfOnesInSubnetMask + 2, zeroCountInSubnetMask + 1).ToString();
        }
        //When Subnet is like 255.0.0.0
        if (zeroCountInSubnetMask > 16 && zeroCountInSubnetMask <= 24)
        {
            broadcastAddressBinary = sb.Replace(CharZero, CharOne, countOfOnesInSubnetMask + 1, zeroCountInSubnetMask + 2).ToString();
        }
        //When Subnet is like 128.0.0.0
        if (zeroCountInSubnetMask > 24 && zeroCountInSubnetMask < 32)
        {
            broadcastAddressBinary = sb.Replace(CharZero, CharOne, countOfOnesInSubnetMask , zeroCountInSubnetMask + 3).ToString();
        }
        return broadcastAddressBinary;
    }

private static string ToIPFromBinary(string ipAddressBinary)
        {
            string addrTemp = string.Empty;
            string[] networkAddressBinaryOctets = ipAddressBinary.Split(SplitterChar);
            foreach (var eachOctet in networkAddressBinaryOctets)
            {
                string temp = Convert.ToUInt32(eachOctet, 2).ToString(CultureInfo.InvariantCulture);
                addrTemp += temp + SplitterChar;
            }
            // remove last '.'
            string ipAddress = addrTemp.Substring(0, addrTemp.Length - 1);
            return ipAddress;
        }
Related