Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Convert netmask in CIDR notation?

Tags:

bash

cidr

netmask

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?

like image 690
Alex_DeLarge Avatar asked May 18 '18 14:05

Alex_DeLarge


1 Answers

  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
like image 111
agc Avatar answered Sep 19 '22 23:09

agc