Check for IP validity

后端 未结 13 1482
庸人自扰
庸人自扰 2020-12-05 07:13

How do I check the validity of an IP address in a shell script, that is within the range 0.0.0.0 to 255.255.255.255?

13条回答
  •  情书的邮戳
    2020-12-05 07:33

    The typical solutions for this all seem to use regular expressions, but it occurs to me that it might be a better approach to do something like:

    if echo "$ip" | { IFS=. read a b c d e;
        test "$a" -ge 0 && test "$a" -le 255 &&
        test "$b" -ge 0 && test "$b" -le 255 &&
        test "$c" -ge 0 && test "$c" -le 255 &&
        test "$d" -ge 0 && test "$d" -le 255 &&
        test -z "$e"; }; then echo is valid; fi
    

提交回复
热议问题