How to validate an IP address

hi

I need a simple script to do the following.

I need to check the user input for

  1. quad dotted notation.
  2. check that all of the inputs are numeric and within 1-255 range.

Could someone please help me?

I tried to use egrep to check for dotted notation.

quad=1.1.1.12
QUAD4=`echo "${quad}" | egrep '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+'`
echo $QUAD4

this validates ok excepts when I have a test ip address as "1.2.2.1a" it fails to validate if and return me the ip adrees itself.

For the second step I have no clue . I would really appreciate if anyone could give any suggestion.

Thanks,
Sabina

Give this a try

#!/bin/sh

echo "Enter IP address"
read quad

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

if [ "$#" -ne "4" ]; then
  echo "Must have 4 parts"
  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 "$oct: Not numeric"
     exit 1
  else
     if [ "$oct" -lt "0" -o "$oct" -gt "255" ]; then
        echo "$oct: Out of range"
        exit 1
     fi
  fi
done

# if we're here, we're validated
echo "$quad validates OK!"
exit 0

Cheers
ZB

Hi ZB

I tried it and it works pertfectly. I really like your code. It look so neat and precise. Thanks a lot for your time. I really appreciate it.

Sabina

Hi ZB

I found a case where if fails.

ip=1.2.3.4.

If we have nothing after last "." if failes to recognize it as invalid ip address.

Thanks,
Sabina

No problem - this should fix it....

#!/bin/sh

echo "Enter IP address"
read quad

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

if [ "$#" -ne "4" ]; then
  echo "Must have 4 parts"
  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 "$oct: Not numeric"
     exit 1
  else
     if [ "$oct" -lt "0" -o "$oct" -gt "255" ]; then
        echo "$oct: Out of range"
        exit 1
     fi
  fi
done

# New code from here....
echo "$quad" | grep "\.$" >/dev/null 2>&1
if [ "$?" -eq "0" ]; then
  echo "Trailing period - invalid"
  exit 1
fi
# to here.....

# if we're here, we're validated
echo "$quad validates OK!"
exit 0

Cheers
ZB

Another IP for which this script would fail: 0.1.2.3

adding this helps:

if [ "$1" -eq "0" ]
then
echo "First octet must not be zero (0)..."
exit 1
fi