How to Get Ping to Report Failure in Linux

Using ping to determine if a host is up is easy; but when you want to report that a host is down, it’s a little more complex.

In Windows, ping will report failure:

ping1

If invoked with the “-t” option, Windows ping will perpetually ping a host, showing success (ping result) or failure (request timed out) each time.

This is really useful for diagnostics on LANs, amongst other rationales.

Unfortunately, the Fedora version (and most Linux flavours) of ping won’t report failure. ¬†Instead, it will silently suppress failed pings until you exit, at which point it will report back the percentage of packet loss.

This is one place Windows beats Linux.

However, with some simple scripting this issue can be resolved:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#!/bin/bash

# Get the host name
var_host=$1

# Check if valid
if [ -z $var_host ]; then
   echo "Syntax: $0 [Host]"
   exit 1
fi

# Repeatedly ping and report result
while :; do
   ping -W 1 -c 1 $var_host | grep "bytes from" > /dev/null

   if [ $? -gt 0 ]; then
      echo "Host $var_host is DOWN."
   else
      echo "Host $var_host is UP."
   fi

   # Keep rate of pings reasonable
   sleep 1
done

The main function is line 14:

ping -W 1 -c 1 $var_host | grep "bytes from" > /dev/null

Some notes:

  • -W” option imposes a “deadline” (timeout in seconds) at which ping automatically exits, even if no results are in yet; here we cap it at 1 second, which is more than reasonable
  • -c” option sets a “count” for the number of packets to send; we send only 1 ping (instead of having ping go forever, we will just do it once, and use the script to loop it)
  • grep ‘bytes from’” searches for that phrase; it will only appear on success, exiting with a return code of 0 (stored in $?).
  • If grep can’t find that phrase, it will exit with a return code of 1
  • Of course, redirecting to > /dev/null suppresses the output

Example of use:

ping2

Of course, you can easily customize the output by changing line 14 to read as follows:

var_result=`ping -W 1 -c 1 $var_host | grep "bytes from"`

Now you have the output in a bash variable, and can manipulate it to show whatever is needed.

That’s it.

k

 

Karim Sultan
My vision is for digital innovation across the divide, by securing and simplifying the Internet and extending its reach to every citizen on Earth and beyond.

Leave a Reply

Your email address will not be published. Required fields are marked *