3

I just noticed the ping command always returns zero exit code in cygwin.

I installed it as a package ping.

Actual output:

$ ping 192.168.0.102 -c 1
PING 192.168.0.102 (192.168.0.102): 0 data bytes
36 bytes from 192.168.0.11: icmp_type=3 (Dest Unreachable) icmp_code=1

----192.168.0.102 PING Statistics----
1 packets transmitted, 0 packets received, 100.0% packet loss

vlastimil@vb-nb-windows ~
$ echo $?
0

Expected output:

$ echo $?
1

This ping package contains non-standard version of ping command, which obviously behaves as described in the question.

I tried to uninstall this package and install inetutils instead, but there seems to be no ping command.

How can I go about solving this issue? (a wrapper, etc.)

EDIT1:

The answer should be written in POSIX for portability. Sorry for forgetting about it.

0

POSIX approach


Cygwin-specific way (wrapper)

# Using ping utility from ping package
# This utility seems to always return 0 exit code
is_host_online_cygwin()
{
    ping_output_raw=$(ping "$1" 64 1)
    ! echo "$ping_output_raw" | grep 'Dest Unreachable' > /dev/null 2>&1
}

Windows-specific way (wrapper) [contest winner]

# Using built-in ping utility
# This utility seems to always return 0 exit code
is_host_online_windows()
{
    ping_output_raw=$(ping -n 1 "$1")
    ! echo "$ping_output_raw" | grep 'Destination host unreachable' > /dev/null 2>&1
}

Linux-specific way (direct)

# Using ping utility from iputils-ping package
# This utility returns the right exit code, there is no need for a wrapper
is_host_online_linux()
{
    ping -c 1 "$1" > /dev/null 2>&1
}

Notes

  • I am aware this solution is by far not ideal, but it works

  • These functions can be simply executed upon finding out what program as ping command we are actually using, and though this is out of the scope of this Q & A, I leave a hint:

    command -v ping
    
  • I chose to uninstall the ping package from Cygwin and use is_host_online_windows() because it is simply faster than the Cygwin program.

  • For completeness, I included is_host_online_linux(), although unrelated to this question.

  • as post info about cygwin ping. The old version was replaced by inetutils version cygwin.com/ml/cygwin-announce/2018-07/msg00012.html. The new version now properly report the failure case $ echo $? 1 – matzeri Oct 21 '18 at 20:47
  • @matzeri Thanks for the feedback. Seems like I will have to do some changes to the answer. Will do that once I'm home. Thanks. – LinuxSecurityFreak Oct 22 '18 at 13:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.