How to convert an IPV4 netmask to CIDR

Posted on

To switch from an IPV4 netmask to the equivalent CIDR it might occur to do the simplest thing, that is to use a nested "case" block or "if" to obtain the equivalent CIDR so much so that the available netmasks or CIDR are only 32 and that is

NetmaskAddress/CIDRAdresses
255.255.255.255a.b.c.d/3220
255.255.255.254a.b.c.d/3120
255.255.255.252a.b.c.d/3021
255.255.255.248a.b.c.d/2922
255.255.255.240a.b.c.d/2823
255.255.255.224a.b.c.d/2724
255.255.255.192a.b.c.d/2625
255.255.255.128a.b.c.d/2526
255.255.255.0a.b.c.0/2427
255.255.254.0a.b.c.0/2328
255.255.252.0a.b.c.0/2229
255.255.248.0a.b.c.0/21210
255.255.240.0a.b.c.0/20212
255.255.224.0a.b.c.0/19213
255.255.192.0a.b.c.0/18214
255.255.128.0a.b.c.0/17215
255.255.0.0a.b.0.0/16216
255.254.0.0a.b.0.0/15217
255.252.0.0a.b.0.0/14218
255.248.0.0a.b.0.0/13219
255.240.0.0a.b.0.0/12220
255.224.0.0a.b.0.0/11221
255.192.0.0a.b.0.0/10222
255.128.0.0a.b.0.0/9223
255.0.0.0a.0.0.0/8224
254.0.0.0a.0.0.0/7225
252.0.0.0a.0.0.0/6226
248.0.0.0a.0.0.0/5227
240.0.0.0a.0.0.0/4228
224.0.0.0a.0.0.0/3229
192.0.0.0a.0.0.0/2230
128.0.0.0a.0.0.0/1231
0.0.0.00.0.0.0/0232
Netmask to CIDR

If we want instead create a function that converts the netmask to CIDR we need to know how to convert a decimal number to binary first.

fromNetmaskToCidr() {
  local netmask=$1
  local bin=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
  local b=''
  local n
  local cidr
  for n in ${netmask//./ }; do
    if [ $n -gt 255 ]; then
      echo -e "\t[ERROR] netmask $netmask format error in '.$n'. I will use .255 insted of .$n"
      n=255
    fi
    if [ $n -ne 0 -a $n -ne 128 -a $n -ne 192 -a $n -ne 224 -a $n -ne 240 -a $n -ne 248 -a $n -ne 252 -a $n -ne 254 -a $n -ne 255 ]; then
      echo -e "\t[ERROR] netmask $netmask format error in '.$n' (it must be 0,128,192,224,240,248,252,254,255). I will use .255 insted of .$n"
      n=255
    fi
    # $b is the binary of $netmask
    b=${b}${bin[$n]}
  done
  # remove right "0" bits from $b
  b=${b/%0*}
  cidr=${#b}
  echo $cidr
}

What we do is convert the 4 octets of the netmask into binary and put them in series in the only variable "b" then remove the 0 bits present on the right of the overall binary number.
Finally, just count the number of bits left to get the CIDR which will then be returned on exit.

References

Leave a Reply

Your email address will not be published. Required fields are marked *