Skip to content

Instantly share code, notes, and snippets.

@coderofsalvation
Last active August 29, 2015 13:56
Show Gist options
  • Save coderofsalvation/8933625 to your computer and use it in GitHub Desktop.
Save coderofsalvation/8933625 to your computer and use it in GitHub Desktop.
ip functions (check whether ip is in given range e.g.)
# ip functions (check whether ip is in given range e.g.)
# collected from https://github.com/caquino/bash-functions/blob/master/network-lib
iscidr () {
[[ ${1} =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/?[0-9]{1,2}?$ ]] && echo $1
}
inet_ntoa () {
[[ ${1} =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] || return 255
IFS=".";set - ${1};unset IFS
local OCT1 OCT2 OCT3 OCT4
OCT1=$(($1<<24));OCT2=$(($2<<16));OCT3=$(($3<<8));OCT4=$4
echo $(($OCT1+$OCT2+$OCT3+$OCT4))
}
inet_aton () {
[[ ${1} =~ ^[0-9]+$ ]] || return 255
ADDRESS=${1}
OCT4=$((${ADDRESS} % 256));ADDRESS=$((${ADDRESS}-${OCT4}));ADDRESS=$((${ADDRESS}/256))
OCT3=$((${ADDRESS} % 256));ADDRESS=$((${ADDRESS}-${OCT3}));ADDRESS=$((${ADDRESS}/256))
OCT2=$((${ADDRESS} % 256));ADDRESS=$((${ADDRESS}-${OCT2}));ADDRESS=$((${ADDRESS}/256))
OCT1=$((${ADDRESS} % 256))
echo "${OCT1}.${OCT2}.${OCT3}.${OCT4}"
}
isipinrange () {
[[ ${1} =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]] || return 255
[[ ${2} =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/?[0-9]{1,2}?$ ]] || return 255
NETWORK=$(inet_ntoa ${2%%/*})
BITMASK=${2##*/}
BITMASK=$((~((1<<(32 - $BITMASK))-1)))
IPDEC=$(inet_ntoa ${1})
IPNET=$((${IPDEC}&${BITMASK}))
[[ ${IPNET} == ${NETWORK} ]] && return 0
return 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment