#! /bin/bash
##check a ip which you type the IP format are right or not
##writen by ASD9577 2017-05-10
checkip()
{
if echo $1 | egrep -q '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'; then
a=`echo $1 | awk -F '.' '{print $1}'`
b=`echo $1 | awk -F '.' '{print $2}'`
c=`echo $1 | awk -F '.' '{print $3}'`
d=`echo $1 | awk -F '.' '{print $4}'`
for i in $a $b $c $d; do
if [ $i -gt 255 ] || [ $i -lt 1 ]; then
echo "the IP $a.$b.$c.$d was wrong pls type a IP which less then 255 and great than 1"
return 2
fi
done
if [ $a -ge 1 ] && [ $a -lt 127 ];then
echo "you input the IP belong to A"
elif [ $a -ge 128 ] && [ $a -lt 192 ];then
echo "you input the IP belong to B"
elif [ $a -ge 192 ] && [ $a -lt 224 ];then
echo "you input the IP belong to C"
elif [ $a -ge 224 ] && [ $a -lt 240 ];then
echo "you input the IP belong to D"
fi
else
echo "the IP format not right pls type the correct IP like '192.168.30.158'"
return 1
fi
}
rs=1
while [ $rs -gt 0 ]; do
read -p "pls type a IP:" ip
checkip $ip
rs=`echo $?`
done
echo "the IP you typed is a valid"
有更好的方法或建议,希望指正!
# 检查IP地址是否合法
check_ip()
{
ret=1
flage=`awk 'BEGIN {if (match(ARGV[1], "^.*:.*$") != 0) print "true"; else print "false"}' $1`
if [ "${flage}" != "true" ]; then
flage=`awk 'BEGIN {n=split(ARGV[1], A, ".");
if (n == 4)
for (i in A)
if ((match(A, "^0$") != 0) ||
(match(A, "^[1-9][0-9]?$") != 0) ||
(match(A, "^1[0-9][0-9]$") != 0) ||
(match(A, "^2[0-4][0-9]$") != 0) ||
(match(A, "^25[0-5]$"))) {res=1;}
else {res=0; break;}
if (res == 1) print "true"; else print "false"}' $1`
if [ "${flage}" = "true" ]; then
ret=0
fi
else
values=`echo $1 |tr '[0-9][a-f][A-F]' '='`
if [ "${values}" != "::" ]; then
flage=`awk 'BEGIN {n=split(ARGV[1], A, ":");
if (n <= 8)
for (i in A)
if (A == "") {if (++cnt > 2) {res=0; break;}}
else if ((length(A) <= 4) && (match(A, "^=+?$") != 0)) {res=1;}
else {res=0; break;}
if (res == 1) print "true"; else print "false"}' ${values}`
if [ "${flage}" = "true" ]; then
ret=0
fi
else
ret=0
fi
fi
return $ret
}
编辑回复