Operating System - HP-UX
1834926 Members
2588 Online
110071 Solutions
New Discussion

Re: Script to validate a IP4 addres

 
SOLVED
Go to solution
Senthil Prabu.S_1
Trusted Contributor

Script to validate a IP4 addres

Hi gurus,
Can any one share with a piece of shell script that validate the user entered IP4 address.

In details, my need is
[a]. Get a IP4 address from user
[b]. Validate whether it is of correct format.

Please reply back ASAP.


Thanks,
Prabu.S
One man's "magic" is another man's engineering. "Supernatural" is a null word.
3 REPLIES 3
Arunvijai_4
Honored Contributor

Re: Script to validate a IP4 addres

Hi Senthil,

How about this,

valid_ip()
(
IFS=.
set -- $1
[ $# -ne 4 ] && return 1
for n
do
case $n in
*[!0-9]* | "") return 1 ;;
esac
[ $n -le 255 ] || return 1
done
)

http://www.codecomments.com/archive287-2005-4-458907.html

-Arun
"A ship in the harbor is safe, but that is not what ships are built for"
Arunvijai_4
Honored Contributor
Solution

Re: Script to validate a IP4 addres

One more script,

#!/bin/sh
#< Simple script to validate IPv4 addresses - use as a filter
# Returns 1 if error, 0 if validation successful
# KW 05/03/05

prog=$(basename ${0})

read input
set -- ${input}
if [ "$#" -ne "1" ]; then
echo "${prog}: Usage: ${prog} ip_address" >&2
exit 1
fi

quad=${1}

oldIFS=${IFS}
IFS=.
set -- ${quad}

if [ "$#" -ne "4" ]; then
echo "${prog}: ip_address must have 4 quads" >&2
exit 1
fi

for oct in ${1} ${2} ${3} ${4}; do
echo ${oct} | egrep "^[0-9]+$" >/dev/null 2>&1
if [ "$?" -ne "0" ]; then
echo "${prog}: ${oct}: not numeric" >&2
exit 1
else
if [ "${oct}" -lt "0" -o "${oct}" -gt "255" ]; then
echo "${prog}: ${oct}: out of range" >&2
exit 1
fi
fi
done

echo "${quad}" | grep "\.$" >/dev/null 2>&1
if [ "$?" -eq "0" ]; then
echo "${prog}: trailing period - invalid" >&2
exit 1
fi

echo "${quad}" | grep "^\." >/dev/null 2>&1
if [ "$?" -eq "0" ]; then
echo "${prog}: leading period - invalid" >&2
exit 1
fi

echo "${quad}" | grep "\.\." >/dev/null 2>&1
if [ "$?" -eq "0" ]; then
echo "${prog}: empty quad - invalid" >&2
exit 1
fi

# if we're here, we're validated
exit 0

Link, http://www.zazzybob.com/bin/valip.html

-Arun
"A ship in the harbor is safe, but that is not what ships are built for"
Senthil Prabu.S_1
Trusted Contributor

Re: Script to validate a IP4 addres

Hi Arun,
Thanks a lot for quick reply.
Second script did the trick.




--
Prabu.S
One man's "magic" is another man's engineering. "Supernatural" is a null word.