Bash - Convert netmask in CIDR notation?

Alex_DeLarge picture Alex_DeLarge · May 18, 2018 · Viewed 8.9k times · Source

Example: I have this netmask: 255.255.255.0

Is there, in bash, a command or a simple script to convert my netmask in notation /24?

Answer

agc picture agc · May 19, 2018
  1. Function using subnetcalc:

    IPprefix_by_netmask() {
        subnetcalc 1.1.1.1 "$1" -n  | sed -n '/^Netw/{s#.*/ #/#p;q}'
    }
    
  2. In pure bash, convert IP to a long octal string and sum its bits:

    IPprefix_by_netmask () { 
       c=0 x=0$( printf '%o' ${1//./ } )
       while [ $x -gt 0 ]; do
           let c+=$((x%2)) 'x>>=1'
       done
       echo /$c ; }
    

Output of IPprefix_by_netmask 255.255.255.0 (either function):

/24