shell校驗ip是否合法

#!/bin/bash

# valid ip
function isValidIp() {
  local ip=$1
  local ret=1

  if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
    ip=(${ip//\./ }) # 按.分割,轉成數組,方便下面的判斷
    [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
    ret=$?
  fi  

  return $ret
}

# get target ip
function getTargetIp() {
	targetIp="127.0.0.1"
	while :
	do
		read -p "Please input target ip:" ip
		if [ ! $ip ]; then
			break # ip爲空,說明沒有輸入,使用默認ip
		fi
		if isValidIp $ip; then
			targetIp=$ip
			break
		else
			echo "$ip is not a valid ip, please retry."
		fi
	done
}

getTargetIp

echo "Target ip is $targetIp"

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章