0

Related:
How to ping in linux until host is known?

On Linux, ping has inconsistent behaviour. If it initially has no network connection, it terminates with the message

user@machine:~$ ping 8.8.8.8
connect: Network is unreachable
user@machine:~$

However, if there is a connection but it is disconnected, it keeps attempting to ping:

user@machine:~$ ping 8.8.8.8
64 bytes from 8.8.8.8: icmp_seq=1 ttl=120 time=37.4 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=120 time=37.4 ms
ping: sendmsg: Network is unreachable
ping: sendmsg: Network is unreachable
ping: sendmsg: Network is unreachable
64 bytes from 8.8.8.8: icmp_seq=6 ttl=120 time=37.8 ms
64 bytes from 8.8.8.8: icmp_seq=7 ttl=120 time=35.1 ms

* ... etc ... *

I often use ping to monitor the status of my internet connection, especially on flaky Wifi, and it would be great to have ping "keep trying" if there is initially no connection. (I tried this on Mac OSX where ping behaves as I would like it to.)

A simple while loop isn't sufficient because ctrl-C handling doesn't work properly.

How can ping be set up on Linux to keep retrying even if there is initially no connection?

Artelius
  • 101
  • 1

1 Answers1

0

Here is my Bash solution, which does a bit of hackery to make Ctrl-C work as expected.

retry_ping() {( #run in subshell, so don't need to reset SIGINT or EXIT variable
  trap "EXIT=1" SIGINT
  while true; do
    ping $1 &
    wait
    if [ $EXIT ]; then
      break
    fi
    sleep 2 #or however long you want
  done
)}

#usage example
retry_ping 8.8.8.8

Or a one-liner:

retry_ping(){(trap "EXIT=1" SIGINT;while true;do ping $1& wait;if [ $EXIT ];then break;fi;sleep 2;done)}

Example output:

user@machine:~$ retry_ping 8.8.8.8
connect: Network is unreachable
connect: Network is unreachable
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=120 time=5.07 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=120 time=3.04 ms
ping: sendmsg: Network is unreachable
ping: sendmsg: Network is unreachable
64 bytes from 8.8.8.8: icmp_seq=5 ttl=120 time=4.04 ms
64 bytes from 8.8.8.8: icmp_seq=6 ttl=120 time=3.10 ms
^C
--- 8.8.8.8 ping statistics ---
6 packets transmitted, 4 received, 33% packet loss, time 5109ms
rtt min/avg/max/mdev = 3.07/4.057/5.07/1.000 ms
Artelius
  • 101
  • 1