SoFunction
Updated on 2025-04-04

How to determine whether the IP address is legal in shell scripts


[root@yang python]# vi check_ip.sh
#!/usr/bin/sh
CheckIPAddr()
{
echo $1|grep "^[0-9]\{1,3\}\.\([0-9]\{1,3\}\.\)\{2\}[0-9]\{1,3\}$" > /dev/null;
#IP address must be full number
        if [ $? -ne 0 ]
        then
                return 1
        fi
        ipaddr=$1
a=`echo $ipaddr|awk -F . '{print $1}'`  #Separated by ".", take out the value of each column
        b=`echo $ipaddr|awk -F . '{print $2}'`
        c=`echo $ipaddr|awk -F . '{print $3}'`
        d=`echo $ipaddr|awk -F . '{print $4}'`
        for num in $a $b $c $d
        do
if [ $num -gt 255 ] || [ $num -lt 0 ]    #Each value must be between 0-255
                then
                        return 1
                fi
        done
                return 0
}
if [ $# -ne 1 ];then              #Judge the number of passed parameters
        echo "Usage: $0 ipaddress."
        exit
else
CheckIPAddr $1
fi