check valid ipv4

This commit is contained in:
Marco Ochse 2017-09-28 13:30:39 +02:00 committed by GitHub
parent e5e8ad4785
commit 65c7d9cc88

View file

@ -34,6 +34,24 @@ httplist=(
whatismyip.akamai.com whatismyip.akamai.com
) )
# function to check for valid ip
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
}
# function to shuffle the global array "array" # function to shuffle the global array "array"
shuffle() { shuffle() {
local i tmp size max rand local i tmp size max rand
@ -45,44 +63,41 @@ shuffle() {
tmp=${array[i]} array[i]=${array[rand]} array[rand]=$tmp tmp=${array[i]} array[i]=${array[rand]} array[rand]=$tmp
done done
} }
# if we have dig and a list of dns methods, try that first # if we have dig and a list of dns methods, try that first
if hash dig 2>/dev/null && [ ${#dnslist[*]} -gt 0 ]; then if hash dig 2>/dev/null && [ ${#dnslist[*]} -gt 0 ]; then
eval array=( \"\${dnslist[@]}\" ) eval array=( \"\${dnslist[@]}\" )
shuffle shuffle
for cmd in "${array[@]}"; do for cmd in "${array[@]}"; do
[ "$verbose" == 1 ] && echo Trying: $cmd 1>&2 [ "$verbose" == 1 ] && echo Trying: $cmd 1>&2
ip=$(timeout $timeout $cmd) ip=$(timeout $timeout $cmd)
if [ -n "$ip" ]; then if [ -n "$ip" ]; then
if valid_ip $ip; then
echo $ip echo $ip
exit exit
fi fi
fi
done done
fi fi
# if we haven't succeeded with DNS, try HTTP # if we haven't succeeded with DNS, try HTTP
if [ ${#httplist[*]} == 0 ]; then if [ ${#httplist[*]} == 0 ]; then
echo "No hosts in httplist array!" >&2 echo "No hosts in httplist array!" >&2
exit 1 exit 1
fi fi
# use curl or wget, depending on which one we find # use curl or wget, depending on which one we find
curl_or_wget=$(if hash curl 2>/dev/null; then echo curl; elif hash wget 2>/dev/null; then echo "wget -qO-"; fi); curl_or_wget=$(if hash curl 2>/dev/null; then echo "curl -s"; elif hash wget 2>/dev/null; then echo "wget -qO-"; fi);
if [ -z "$curl_or_wget" ]; then if [ -z "$curl_or_wget" ]; then
echo "Neither curl nor wget found. Cannot use http method." >&2 echo "Neither curl nor wget found. Cannot use http method." >&2
exit 1 exit 1
fi fi
eval array=( \"\${httplist[@]}\" ) eval array=( \"\${httplist[@]}\" )
shuffle shuffle
for url in "${array[@]}"; do for url in "${array[@]}"; do
[ "$verbose" == 1 ] && echo Trying: $curl_or_wget -s "$url" 1>&2 [ "$verbose" == 1 ] && echo Trying: $curl_or_wget "$url" 1>&2
ip=$(timeout $timeout $curl_or_wget -s "$url") ip=$(timeout $timeout $curl_or_wget "$url")
if [ -n "$ip" ]; then if [ -n "$ip" ]; then
if valid_ip $ip; then
echo $ip echo $ip
exit exit
fi fi
fi
done done