Skip to content

Instantly share code, notes, and snippets.

@gswallow
Last active September 24, 2020 10:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gswallow/5586747 to your computer and use it in GitHub Desktop.
Save gswallow/5586747 to your computer and use it in GitHub Desktop.
Find netmask / network address / broadcast address / supposed gateway from an IP/cidr pair
cidr2mask() {
local mask=""
local netaddr=""
local bcast=""
local gateway=""
local full_octets=$(($2/8))
local partial_octet=$(($2%8))
ipparts=($(echo $1 | tr "." "\n"))
for ((i=0;i<4;i+=1)); do
if [ $i -lt $full_octets ]; then
mask+=255
netaddr+=${ipparts[$i]}
bcast+=${ipparts[$i]}
gateway+=${ipparts[$i]}
elif [ $i -eq $full_octets ]; then
mask+=$((256 - 2**(8-$partial_octet)))
netaddr+=$(( ${ipparts[$i]} - ( ${ipparts[$i]} % ( 2 ** ( 8 - $partial_octet )) ) ))
bcast+=$(( ${ipparts[$i]} + (2**(8-$partial_octet) - (${ipparts[$i]} % (2**(8-$partial_octet) ))) - 1))
if [ $i -lt 3 ]; then
gateway+=$(( ${ipparts[$i]} - ( ${ipparts[$i]} % ( 2 ** ( 8 - $partial_octet ) )) ))
else
gateway+=$(( ${ipparts[$i]} - ( ${ipparts[$i]} % ( 2 ** ( 8 - $partial_octet ) )) +1 ))
fi
else
mask+=0
gateway+=1
netaddr+=0
bcast+=255
fi
test $i -lt 3 && mask+=.
test $i -lt 3 && netaddr+=.
test $i -lt 3 && bcast+=.
test $i -lt 3 && gateway+=.
done
echo $mask $netaddr $bcast $gateway
}
# Confirm that the IP address is address/mask
addrmask=$1
if [ `expr index "$addrmask" '/'` -eq "0" ]; then
usage
fi
ip=${addrmask%/*}
cidrmask=${addrmask#*/}
if [ `expr match "$ip" '.*[^0-9.]'` -gt "0" ]; then
echo "Wrong IP format."
usage
fi
if [ `expr match "$cidrmask" '.*[^0-9]'` -gt "0" ]; then
echo "Wrong netmask format."
usage
fi
echo $ip $cidrmask
tuple=(`cidr2mask $ip $cidrmask`)
netmask=${tuple[0]}
network=${tuple[1]}
bcast=${tuple[2]}
gateway=${tuple[3]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment