Hi does anybody have a ksh/sh/bash function that i can embed into my script that i could use to validate an inputted IP address, I tried using one big long regular expression but it got very long and complicated
ie
#!/bin/ksh
echo " Please enter your IP address"
read IP
---some function to determine if it is valid or not
valid_dotted_quad()
{
ERROR=0
oldIFS=$IFS
IFS=.
set -f
set -- $1
if [ $# -eq 4 ]
then
for seg
do
case $seg in
""|*[!0-9]*) ERROR=1;break ;; ## Segment empty or non-numeric char
*) [ $seg -gt 255 ] && ERROR=2 ;;
esac
done
else
ERROR=3 ## Not 4 segments
fi
IFS=$oldIFS
set +f
return ERROR
}
Test $IP with:
if valid_dotted_quad "$IP"
then
## IP OK
else
## Not OK
printf "%s is not a valid dotted quad IP address" "$IP" >&2
fi
Note, however, that other formats can be valid IP addresses.