7

My ping command (on Debian 6 or 7) will repeatedly attempt to ping a server even while the network is down, if the network was up when it was started. Is there some way to start ping while the network is down and get this same behavior?

Here's an example. If I start a repeating ping while the network is up, and while the ping is running, the network goes down, the ping continues to repeat. If the network comes back up, it will continue pinging:

me@here:~$ ping -n 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_req=1 ttl=46 time=117 ms
...
64 bytes from 8.8.8.8: icmp_req=6 ttl=46 time=116 ms
ping: sendmsg: Network is unreachable
...
ping: sendmsg: Network is unreachable
64 bytes from 8.8.8.8: icmp_req=108 ttl=46 time=694 ms
...

However, if the network is down when I run ping:

me@here:~$ ping -n 8.8.8.8
connect: Network is unreachable
me@here:~$

This is the same unreachable network problem, but ping doesn't keep trying until the network is up again, like it had before.

3 Answers 3

7

You can use a while loop in a shell script:

failed=1 # any number not equal to zero
while [ $failed -ne 0 ]
do
   ping -n 8.8.8.8
   failed=$?
done
# after the  $? becomes "0" it will get out of the while loop
echo "ping succeeded"

To stop keep printing the connect: Network is unreachable message you can edit the line with ping like this:

ping -n 8.8.8.8 2> /dev/null

Or you can add a sleep in the loop to reduce the number of those messages.

The script can be simplified to

while ! ping -n 8.8.8.8
do
    sleep 1
done

Which lets it be written in one line:

while ! ping -n 8.8.8.8; do sleep 1; done
1
  • An advantage to this solution is that you can use the -a option to hear beeps as soon as the network comes up. A disadvantage is that in the final statistics, the early failures are not counted.
    – Dan Getz
    Commented Jun 18, 2014 at 15:56
2

AFAICT, ping will not run if it cannot open a socket on an interface (because the interface is down). If you check your devices with ip link show, you will see which devices are up or down.

Try activating the network device first.

$ sudo ip link set <iface> up
$ ping -n 8.8.8.8

I've tested this on my Arch Linux box with a down wifi interface, and an up virtual ethernet (no IP address assigned) interface. A ping on the former quits, while the latter ping is continuous.

Otherwise, use networker's shell script.

1

You can use fping with its -l and -I options, instead of ping. This requires knowing the name of the interface, and running as root:

root@here:~# fping -l -I wlan0 -n 8.8.8.8

me@here:~$ sudo fping -l -I eth0 -n 8.8.8.8

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .