converting netmask to CIDR or vice verse

#!/bin/bash
# convert netmask to CIDR (Classless Inter-Domain Routing) or vice verse
#

mask2cidr ()
{
   # Assumes there's no "255." after a non-255 byte in the mask
   local x=${1##*255.}
   set -- 0^^^128^192^224^240^248^252^254^ $(( (${#1} - ${#x})*2 )) ${x%%.*}
   x=${1%%$3*}
   echo $(( $2 + (${#x}/4) ))
}

cidr2mask ()
{
   # Number of args to shift, 255..255, first non-255 byte, zeroes
   set -- $(( 5 - ($1 / 8) )) 255 255 255 255 $(( (255 << (8 - ($1 % 8))) & 255 )) 0 0 0
   [ $1 -gt 1 ] && shift $1 || shift
   echo ${1-0}.${2-0}.${3-0}.${4-0}
}

showUsage ()
{
    echo "Usage: $0 <m2c netmask | c2m CIDR-prefix-bits>"
    echo "Example: $0 m2c 255.255.255.0"
    echo "Example: $0 c2m 24"
}

if [ $# != 2 ]; then 
    showUsage
    exit 1 
fi

if [ $1 = "m2c" ]; then
    mask2cidr $2
elif [ $1 = "c2m" ]; then
    cidr2mask $2
else
    showUsage
fi

reference
https://stackoverflow.com/questions/20762575/explanation-of-convertor-of-cidr-to-netmask-in-linux-shell-netmask2cdir-and-cdir

Leave a Reply

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