Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save aachyee/7190fbc24531c509709e93418bd396dc to your computer and use it in GitHub Desktop.

Select an option

Save aachyee/7190fbc24531c509709e93418bd396dc to your computer and use it in GitHub Desktop.
convert between cidr and netmask
#!/bin/bash
# src: https://stackoverflow.com/questions/20762575/explanation-of-convertor-of-cidr-to-netmask-in-linux-shell-netmask2cdir-and-cdir
mask2cidr ()
{
# 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) ))
}
cidr2mask ()
{
# 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}
}
# cidr2mask 16 => 255.255.0.0
# mask2cidr 255.255.0.0 => 16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment