Tuesday, September 11, 2012

Using bash check IP validity

The following snippet of code is to use to check IP address validity.

#!/bin/bash

usage () {
echo "incorrect IP format."
readip
chkip
}
readip () {
read -p "Your IP: " IP
 }
 chkip () {
 echo "$IP" | grep -Eq '[^0-9.]|^\.|\.$' && usage
 echo "execute once"
 [ $(echo -e "${IP//./\n}" | wc -l) -ne 4 ] && usage
 for i in ${IP//./ } ; do
 [ $((i/8)) -lt 32 ] || usage
 done
 }

 if [ "$1" ]; then
 IP=$1
 else
 readip
 fi
 chkip
 echo "$IP is good!"



Note: the grep command option -E is to use extended regular expression which is similarto most recent regular expression. It supports more meta characters. References: Posix Extended Regular Expression

note: POSIX ERE Alternation Returns The Longest Match plus pre-condition is the leftmost.

No comments:

Post a Comment