Bernard
Bernard

Reputation: 1229

Ping function having undesirable results

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

Upvotes: 1

Views: 561

Answers (2)

deceze
deceze

Reputation: 522042

$ 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.

Upvotes: 1

user142162
user142162

Reputation:

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";
}

Upvotes: 1

Related Questions