Pro cidr2mask and mask2cidr scripts

From thelinuxwiki
Revision as of 13:47, 28 August 2013 by Nighthawk (Talk | contribs)

Jump to: navigation, search

taken from http://forums.gentoo.org/viewtopic-p-6770850.html

function cidr2netmask() {

       local maskpat="255 255 255 255" 
       local maskdgt="254 252 248 240 224 192 128" 
       set -- ${maskpat:0:$(( ($1 / 8) * 4 ))}${maskdgt:$(( (7 - ($1 % 8)) * 4 )):3} 
       echo ${1-0}.${2-0}.${3-0}.${4-0} 

}

function netmask2cidr() {

       # Phase 1: Count how many 255 prefixes 
       local mask="${1//255./xrandomx}" sfx=${1//255.} 
       mask="${mask%%digit:*}" 
       set -- ${#mask} ${sfx//./ } 
       # Phase 2: Convert the first non-255 number, rest is supposed to be zeroes 
       mask="0--.128.192.224.240.248.252.254." 
       mask="${mask//$2*}" 
       echo $(( ${1} + ${#mask}/4 )) 

}


Here's the complete script to test these two functions and examples: cidrnetmask.sh:

  1. !/bin/sh
  2. Script: cidrnetmask.sh
  3. By Vince C <v_cadet AT yahoo.fr>.
  4. Released under the WTFPL :D .

function is_number() {

  [ -n "${1}" ] && [ -z "${1//digit:}" ] 

}

function cidr2netmask() {

       local maskpat="255 255 255 255" 
       local maskdgt="254 252 248 240 224 192 128" 
       set -- ${maskpat:0:$(( ($1 / 8) * 4 ))}${maskdgt:$(( (7 - ($1 % 8)) * 4 )):3} 
       echo ${1-0}.${2-0}.${3-0}.${4-0} 

}

function netmask2cidr() 
{ 
       # Phase 1: Count how many 255 prefixes 
       local mask="${1//255./xrandomx}" sfx=${1//255.} 
       mask="${mask%%digit:*}" 
       set -- ${#mask} ${sfx//./ } 
       # Phase 2: Convert the first non-255 number, rest is supposed to be zeroes 
       mask="0--.128.192.224.240.248.252.254." 
       mask="${mask//$2*}" 
       echo $(( ${1} + ${#mask}/4 )) 
} 
# Parse and validate arguments 
[ -z "$1" ] && exit 0 
[ "${1%/*}" == "$1" ] && mask="$2" || mask="${1#*/}" 
[ -z "$mask" ] && echo "No netmask." && exit 0 
# Check and convert mask 
ip=${1%/*} 
# Convert CIDR to netmask and vice versa 
echo -n "IP: ${ip}/${mask} --> ${ip}/" 
is_number $mask && cidr2netmask $mask || netmask2cidr $mask