Pro cidr2mask and mask2cidr scripts

From thelinuxwiki
Jump to: navigation, search
taken from   http://forums.gentoo.org/viewtopic-p-6770850.html


plugable bash functions

# Function takes two arguments, 1st arg= netmask variable, 2nd arg = return variable name
# i.e. 
# netmask2cidr $MASK CIDR
netmask2cidr() { local returnval=$2 # 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*}" local result=`echo $(( ${1} + ${#mask}/4 ))` eval $returnval="'$result'" }

similar to above, but opposite conversion

# function to perform cidr to dot netmask conversion
cidr2netmask() 
{ 
       local returnval=$2
       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} 
       local result=`echo ${1-0}.${2-0}.${3-0}.${4-0}`
       eval $returnval="'$result'"
} 


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

#!/bin/sh 
# Script: cidrnetmask.sh 
# By Vince C <v_cadet AT yahoo.fr>. 
# 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