Check for IP validity

后端 未结 13 1470
庸人自扰
庸人自扰 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:53

    The script Validating an IP Address in a Bash Script by Mitch Frazier does what you want to do:

    function valid_ip()
    {
    local  ip=$1
    local  stat=1
    
    if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        OIFS=$IFS
        IFS='.'
        ip=($ip)
        IFS=$OIFS
        [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
            && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
        stat=$?
    fi
    return $stat
    }
    

提交回复
热议问题