Check for IP validity

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

    You can just copy the following code and change body of if else control as per your need

    function checkIP(){
    echo "Checking IP Integrity"    
    ip=$1
    byte1=`echo "$ip"|xargs|cut -d "." -f1`
    byte2=`echo "$ip"|xargs|cut -d "." -f2`
    byte3=`echo "$ip"|xargs|cut -d "." -f3`
    byte4=`echo "$ip"|xargs|cut -d "." -f4`
    
    
    if [[  $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$  && $byte1 -ge 0 && $byte1 -le 255 && $byte2 -ge 0 && $byte2 -le 255 && $byte3 -ge 0 && $byte3 -le 255 && $byte4 -ge 0 && $byte4 -le 255 ]]
    then
        echo "IP is correct"
    else
        echo "This Doesn't look like a valid IP Address : $ip" 
    fi
    }
    checkIP $myIP 
    

    Calling the method with IP Address stored in a variable named myIP.

    $ip =~ ^[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}$ - This part makes sure that IP consists of 4 blocks separated by a dot(.) but every block here is allowed to range from 0 - 999

    Since desired range of every block would be 0 - 255, to make sure of that below line can be used.

    $byte1 -ge 0 && $byte1 -le 255 && $byte2 -ge 0 && $byte2 -le 255 && $byte3 -ge 0 && $byte3 -le 255 && $byte4 -ge 0 && $byte4 -le 255

提交回复
热议问题