Usage: ./ipvalidator <IP address>
Example: ./ipvalidator 192.168.15.16
This script is using bc (bash calculator) to convert octets to binary number and a simple while loop to scale the binary number to 8 digits.
TIP: If you want to convert any numeral system to decimal number in bash you can use following command:
echo $(( 2#101011 )) to convert binary number to decimal
echo $(( 16#5E3 )) to convert hex number to decimal
Here's the script:
#!/bin/bash echo INPUT IP: $1 OCT=0; for OCTSUB in $( echo $1 | sed -e 's/\./ /g' ); do let OCT=$OCT+1; if [ $OCT -gt 4 ]; then echo The address is too long! exit 1 fi if [[ $OCTSUB != [0-9]* ]] || [ $OCTSUB -gt 255 ]; then echo The $OCT. octet is out of range \($OCTSUB is not valid number\); exit 1 fi done if [ $OCT -lt 4 ]; then echo The address is too short! exit 1 fi echo -e IP Address: $1 is valid! echo -n "Binary Address: " for BINNUM in $( echo $1 | sed -e 's/\./ /g' ); do BINNUM="`echo "ibase=10; obase=2; $BINNUM" | bc`"; while [ "`echo "${#BINNUM}"`" -lt 8 ]; do BINNUM=0$BINNUM done BINRES=$BINRES.$BINNUM done BINRES="`echo -e $BINRES | sed -e 's/\.//'`" echo $BINRES CLASS=(`echo $BINRES | tr '.' "\n" | head -n 1 | sed -e 's/[0-1]/& /g'`) if [ ${CLASS[0]} -eq 0 ]; then VALID=A elif [ ${CLASS[1]} -eq 0 ]; then VALID=B elif [ ${CLASS[2]} -eq 0 ]; then VALID=C elif [ ${CLASS[3]} -eq 0 ]; then VALID=D else VALID=E fi echo This is valid $VALID class address. echo "" exit 0
No comments:
Post a Comment