Ping功能有不良后果

时间:2012-01-17 23:44:13

标签: php

我之前就如何创建ping函数问了这个问题here,并提出了以下建议:

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

直到我注意到它将IP地址192.168.0.3恢复为活着状态才知道它不是。

我检查了我的标准Windows命令提示符,它返回以下内容:

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.

我假设函数认为它的存活是由于它的编写方式以及它如何返回'Reply from'?但是我不太确定 - 有人能说清楚吗?

由于

2 个答案:

答案 0 :(得分:1)

该类错误的退出值不是1,因此您的情况会产生不良后果。请尝试以下方法:

if ($status == 0) {
    $status = "alive";
} else {
    $status = "dead";
}

答案 1 :(得分: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.

您应该检查0的返回代码,而不是!= 1