Skip to content

Instantly share code, notes, and snippets.

@robinsmidsrod
Created April 11, 2015 20:59
Show Gist options
  • Save robinsmidsrod/fe006080bf5b12e0151a to your computer and use it in GitHub Desktop.
Save robinsmidsrod/fe006080bf5b12e0151a to your computer and use it in GitHub Desktop.
Calculate IPv4 network address and CIDR mask from IP address (dotted quad) and network mask (dotted quad)
# $1 is a decimal number between 0-255
dec2bin () {
[ -z "$1" ] && return
D2B=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
echo ${D2B[$1]}
}
# $1 is ip address (dotted quad)
# $2 is netmask (dotted quad)
calc_network () {
[ -z "$1" ] && return
[ -z "$2" ] && return
IFS=. read -r i1 i2 i3 i4 <<< "$1"
IFS=. read -r m1 m2 m3 m4 <<< "$2"
full_mask_bin="$(dec2bin $m1 )$(dec2bin $m2 )$(dec2bin $m3)$(dec2bin $m4)"
mask_bin=$(sed -r 's/0*$//' <<< "$full_mask_bin")
printf "%d.%d.%d.%d/%s\n" \
"$((i1 & m1))" \
"$((i2 & m2))" \
"$((i3 & m3))" \
"$((i4 & m4))" \
${#mask_bin}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment