Reputation: 33
Shell Script (Bash) to Find IP Range of a Network
I am trying to create a shell script to automatically find what the IP Address range is of a network. So far I ran the comamnd:
ifconfig | awk '/broadcast/'
This creates the output:
inet 192.168.1.228 netmask 255.255.255.0 broadcast 192.168.1.255
I'd like for the shell script to take the numbers provided (which I believe is enough to find a range of IP Addresses, but correct me if im wrong) and basically just output a range so for me I think it would be either of these options:
192.168.1.0/24
192.168.1.0-255
192.168.1.*
If this is the way to find an IP Range, then can anyone help me figure out how to display it as a simple output like one of the three options I mentioned before? If this is not the way to find an IP Range, could you please explain how the most accurate way to accomplish this would be. I'm trying to understand networking and shell scripting more so any help would be greatly apprecaiated.
Upvotes: 1
Views: 1543
Reputation: 1391
Well, if you are going to use ifconfig, then it should be something like this:
BARRAY=({0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1}{0..1})
PARAMS=$(ifconfig wlan0 | grep netmask | awk '{print $2" "$4}')
IP_ADDRESS=${PARAMS%% *}
IP_ADDRESS=${IP_ADDRESS//./ }
BINARY_IP_ADDRESS=$(for octet in $IP_ADDRESS; do echo -n ${BARRAY[octet]}" "; done)
BIN_IP_SEP1=${BINARY_IP_ADDRESS//1/1 }
BINARY_IP_ARRAY=( ${BIN_IP_SEP1//0/0 } )
NETMASK=${PARAMS#* }
NETMASK=${NETMASK//./ }
BINARY_NETMASK=$(
for octet in $NETMASK
do
echo -n ${BARRAY[octet]}" "
done
)
BIN_MASK_SEP1=${BINARY_NETMASK//1/1 }
BINARY_MASK_ARRAY=( ${BIN_MASK_SEP1//0/0 } )
# Count bits in MASK ARRAY
BITS_COUNT=0
for i in ${BINARY_MASK_ARRAY[@]}
do
[ "$i" == "1" ] && BITS_COUNT=$((BITS_COUNT + 1))
done
# Count address
NEW_ADDRESS=""
for i in {0..31}
do
[ $(($i % 8)) -ne 0 ] || NEW_ADDRESS+=" "
if [ "${BINARY_MASK_ARRAY[$i]}" == "1" ]
then
NEW_ADDRESS+="${BINARY_IP_ARRAY[$i]}"
else
NEW_ADDRESS+="${BINARY_MASK_ARRAY[$i]}"
fi
done
# Convert binary to decimal
DECIMAL_ADDRESS=`echo $(for octet in $NEW_ADDRESS; do echo $((2#$octet)); done)`
DECIMAL_ADDRESS=${DECIMAL_ADDRESS// /.}
# Final result
echo $DECIMAL_ADDRESS/$BITS_COUNT
If you are going to use "ip addr show" then just correct PARAMS calculations according to received data. Anyway, only this line uses external commands, the rest of the script is in pure bash. I hope it helps.
Upvotes: 1