Check for IP validity

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

    In the most simple form:-

    #!/bin/bash
    while true;
    do
    read -p "Enter a ip: " IP
    echo "${IP}" > ip.txt
    OCT1=$(cat ip.txt | awk -F "." '{print $1}')
    OCT2=$(cat ip.txt | awk -F "." '{print $2}')
    OCT3=$(cat ip.txt | awk -F "." '{print $3}')
    OCT4=$(cat ip.txt | awk -F "." '{print $4}')
    REGEX_IP='^[0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}[.][0-9]{1,3}$'
    if [[ ${IP} =~ ${REGEX_IP} ]]
    then
        if [[ ${OCT1} -gt 255 || ${OCT2} -gt 255 || ${OCT3} -gt 255 || ${OCT4} -gt 255 ]]
            then
            echo "Please enter a valid ip"
            continue
            fi
    
    break
    else
            echo "Please enter a valid ip"
            continue
    fi
    done
    

    This will cover all the scenarios.

提交回复
热议问题