判断ip是否合法+linux,Shell脚本判断IP地址是否合法的方法

使用shell校验ip地址合法性

使用方法:

[root@yang python]# bash check_ip.sh ip地址

执行结果:返回值0校验合法,非0不合法。

shell代码:

[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地址必须为全数字

if [ $? -ne 0 ]

then

return 1

fi

ipaddr=$1

a=`echo $ipaddr|awk -f . '{print $1}'`  #以"."分隔,取出每个列的值

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 ]    #每个数值必须在0-255之间

then

return 1

fi

done

return 0

}

if [ $# -ne 1 ];then            #判断传参数量

echo "usage: $0 ipaddress."

exit

else

checkipaddr $1

fi

你可能感兴趣的:(判断ip是否合法+linux)