Wrong ping response

2

Considering that ${parameters} is an array that can contain valid IP addresses or not, I wrote the following code:

  for ((i=0; i<$#; i++)); do
        eval "arg=\${$i}" 
        ping ${parameters[i]} -c1 -q &>/dev/null
        if [ $? == 0 ]
            then
            echo "ok" 
        else
            echo "fail"
        fi
    done

It turns out that the $? return always seems to contain the value 0 , even when the IP passed in ${parameters[i]} is not valid.

Any ideas?

    
asked by anonymous 19.09.2016 / 05:19

1 answer

2

The error code returned by the ping utility may vary depending on what happened:

  

Success : 0

     

Timed-out : 1

     

Unreachable Host : 2

So here's the example (tested) of a script that can solve your problem:

#!/bin/bash

IP_LIST=( 0.0.0.0
          255.255.255.255
          xxx.xxx.xxx.xxx
          127.0.0.1
          172.217.29.46
          191.239.213.197
          17.172.224.47
          198.175.116.54 )

for ((i = 0; i < ${#IP_LIST[@]}; i++)); do

    ping -q -c1 "${IP_LIST[i]}" &>/dev/null

    case "$?" in
        '0') STATUS="OK" ;;
        '1') STATUS="TIMEOUT" ;;
        '2') STATUS="INALCANCAVEL" ;;
          *) STATUS="ERRO" ;;
    esac

    echo "IP: ${IP_LIST[i]} [${STATUS}]"

done

Output:

IP: 0.0.0.0 [OK]
IP: 255.255.255.255 [INALCANCAVEL]
IP: xxx.xxx.xxx.xxx [INALCANCAVEL]
IP: 127.0.0.1 [OK]
IP: 172.217.29.46 [TIMEOUT]
IP: 191.239.213.197 [TIMEOUT]
IP: 17.172.224.47 [TIMEOUT]
IP: 198.175.116.54 [TIMEOUT]

A more reliable and robust method to solve your problem would be through the availability rate of each IP in the list.

Here is an example of how to calculate the IPs availability rate of a list:

#!/bin/bash

IP_LIST=( 8.8.8.8
          127.0.0.1
          10.1.1.19
          172.217.29.46
          191.239.213.197
          17.172.224.47
          198.175.116.54 )

for ((i = 0; i < ${#IP_LIST[@]}; i++)); do

    PCKT_LOSS=$(ping -q -c5 "${IP_LIST[i]}" | grep -oP '\d+(?=% packet loss)')

    echo "IP: ${IP_LIST[i]} [Disponibilidade: $[100 - ${PCKT_LOSS}]%]"

done

Output:

IP: 8.8.8.8 [Disponibilidade: 0%]
IP: 127.0.0.1 [Disponibilidade: 100%]
IP: 10.1.1.19 [Disponibilidade: 100%]
IP: 172.217.29.46 [Disponibilidade: 0%]
IP: 191.239.213.197 [Disponibilidade: 0%]
IP: 17.172.224.47 [Disponibilidade: 0%]
IP: 198.175.116.54 [Disponibilidade: 0%]

I hope I have helped!

    
19.09.2016 / 21:08