Skip to content

Instantly share code, notes, and snippets.

@atcasanova
Last active October 17, 2019 13:53
Show Gist options
  • Save atcasanova/ec5d2daadfd2bce7138b75dcbdf6146d to your computer and use it in GitHub Desktop.
Save atcasanova/ec5d2daadfd2bce7138b75dcbdf6146d to your computer and use it in GitHub Desktop.
Script to check whether one ip/subnet is within another ip/subnet
#!/bin/bash
(( $# != 2 )) && {
echo "uso: ./$0 10.0.0.0/8 10.10.10.10/24"
exit 1
}
IFS="/" read ip1 mask1 <<< $1
IFS="/" read ip2 mask2 <<< $2
size=$mask1
readarray -d'.' -t first <<< $ip1
readarray -d'.' -t second <<< $ip2
binary=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
zeroes=00000000000000000000000000000000
ones=11111111111111111111111111111111
mask2=$(echo ${ones::$mask2}${zeroes:$mask2}|sed 's/.\{8\}/\0./g'| sed 's/\.$//g')
mask1=$(echo ${ones::$mask1}${zeroes:$mask1}|sed 's/.\{8\}/\0./g'| sed 's/\.$//g')
readarray -d'.' -t firstmask <<< $mask1
readarray -d'.' -t secondmask <<< $mask2
for i in {0..3}; do
answ=${binary[$(( 2#${firstmask[$i]} & 2#${secondmask[$i]} ))]}
((2#$answ == 2#${firstmask[$i]})) || {
echo "$2 nao cabe em $1"
exit 1;
}
done
for i in {0..3}; do
maior+=${binary[${first[$i]}]}
menor+=${binary[${second[$i]}]}
done
(( ${maior::$size} == ${menor::$size} )) && echo "$2 cabe em $1" || echo "$2 nao cabe em $1"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment