1

I previously asked this question here on how to create a ping function and came up with the follow:

<?php
function pingAddress($ip) {
    $pingresult = exec("ping -n 3 $ip", $outcome, $status);
    if (1 != $status) {
        $status = "alive";
    } else {
        $status = "dead";
    }
    echo "The IP address, $ip, is  ".$status;
}

This had the desired results until I noticed that it was returning IP address 192.168.0.3 as alive when I knew it wasn't.

I checked through my standard windows command prompt and it was returning the following:

Reply from 192.168.0.2: Destination host unreachable.
Reply from 192.168.0.2: Destination host unreachable.
Reply from 192.168.0.2: Destination host unreachable.
Reply from 192.168.0.2: Destination host unreachable.

I'm assuming that the function think its alive due to the way its written and how it returns 'Reply from'? However I'm not too sure - can anyone shed some light on it?

Thanks

Community
  • 1
  • 1
Bernard
  • 1,209
  • 3
  • 17
  • 22

2 Answers2

1

Its exit value for that type of error is not 1, therefore your condition would have undesired results. Try the following:

if ($status == 0) {
    $status = "alive";
} else {
    $status = "dead";
}
  • I've changed the exit value accordingly but still getting identical results (192.168.0.3 returning alive although destination unreachable) – Bernard Jan 18 '12 at 00:19
  • @Bernard: Under which system are you running `ping`? –  Jan 18 '12 at 00:23
  • @Bernard: The version of `ping` included in Windows is exiting with a status of `0` for me as well, with those arguments. Doing a `strpos` for the string `Destination host unreachable.` would be an alternative to checking the exit status. –  Jan 18 '12 at 00:35
1
$ man ping

...

RETURN VALUES
     The ping utility returns an exit status of zero if at least one response
     was heard from the specified host; a status of two if the transmission
     was successful but no responses were received; or another value (from
     <sysexits.h>) if an error occurred.

You should be checking for a return code of 0, not != 1.

deceze
  • 510,633
  • 85
  • 743
  • 889