How to convert an IPV4 netmask to CIDR

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

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"
    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"
    # $b is the binary of $netmask
  # remove right "0" bits from $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.


Leave a Reply

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

3 × = 30