OpenWrt Forum Archive

Topic: Convert netmask IP format <--> Nbr of set bits

The content of this topic has been archived on 10 Apr 2018. There are no obvious gaps in this topic, but there may still be some posts missing at the end.

in  the config of the firewall rules (/etc/config/firewall)

the dest_ip and its mask are saved in this way.

the netmask is saved with  the number of set bit format.

 option 'dest_ip' '1.1.1.0/24' 

how I can convert the "24" to 255.255.255.0 (IP address format) with ash script of openwrt. Are there a predefined function that convert :

 24 to 255.255.255.0 

and are there another function that do the inverse. I mean convert

 255.255.255.0 to 24 

(Last edited by kallel on 23 Dec 2013, 16:42)

dunno if there are predefined function, but you could use this:

#/bin/sh
mask2cdr ()
{
   # 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) ))
}


cdr2mask ()
{
   # 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}
}

# examples:
mask2cdr 255.255.255.0
cdr2mask 24

thnx to this thread: http://forums.gentoo.org/viewtopic-t-88 … art-0.html

Thank you very much

FriedZombie wrote:

dunno if there are predefined function, but you could use this:

#/bin/sh
mask2cdr ()
{
   # 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) ))
}


cdr2mask ()
{
   # 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}
}

# examples:
mask2cdr 255.255.255.0
cdr2mask 24

thnx to this thread: http://forums.gentoo.org/viewtopic-t-88 … art-0.html

The discussion might have continued from here.