archwhite
3/9/2016 - 3:41 PM

Convert subnet mask v4 to CIDR (int) notation

Convert subnet mask v4 to CIDR (int) notation

static int Mask2CIDR(string subnetmask)
{
    try
    {
        Byte[] ipbytes = IPAddress.Parse(subnetmask).GetAddressBytes();

        uint subnet = 16777216 * Convert.ToUInt32(ipbytes[0]) +
            65536 * Convert.ToUInt32(ipbytes[1]) + 256 * Convert.ToUInt32(ipbytes[2]) + Convert.ToUInt32(ipbytes[3]);
        uint mask = 0x80000000;
        uint subnetConsecutiveOnes = 0;

        for (int i = 0; i < 32; i++)
        {
            if (!(mask & subnet).Equals(mask)) break;

            subnetConsecutiveOnes++;
            mask = mask >> 1;
        }

        return (int)subnetConsecutiveOnes;
    }
    catch
    {
        return -1;
    }
}