1

我在路由器 (192.168.200.254) 后面的公司局域网上 ping 几台计算机 (192.168.200.1 和 192.168.200.2)。

function pingAddress($TEST) {
$pingresult = exec("ping -n 1 $TEST", $output, $result);
    if ($result == 0) {
        echo "Ping successful!";
        } else {
        echo "Ping unsuccessful!";
        }

    }
pingAddress("192.168.220.1");
pingAddress("192.168.220.2");

我的问题是其中一台计算机未开机( .1 ),但我仍然收到 ping 响应。

Pinging 192.168.200.1 with 32 bytes of data:
Reply from 192.168.200.254: Destination host unreachable.
Ping statistics for 192.168.200.1:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),

192.168.220.1 ping 尝试上的 var_dump($output) 显示为:

array(6) { 
[0]=> string(0) "" 
[1]=> string(44) "Pinging 192.168.200.1 with 32 bytes of data:" 
[2]=> string(57) "Reply from 192.168.200.254: Destination host unreachable." 
[3]=> string(0) "" 
[4]=> string(34) "Ping statistics for 192.168.200.1:" 
[5]=> string(56) " Packets: Sent = 1, Received = 1, Lost = 0 (0% loss)," 
}

所以我改为尝试搜索为误报“目标主机无法访问”消息创建的 $output 数组,但这条路线没有运气。

function pingAddress($TEST) {
$findme ="Destination host unreachable";

    $pingresult = exec("ping -n 1 $TEST  && exit", $output, $result);
        //echo $result. "<br/>";
        if (($result == 0) AND (in_array($findme, $output))){
            echo "Ping unsuccessful! <br/>";
        }
        elseif (($result == 0) AND (!in_array($findme, $output))){
            echo "Ping successful! <br/>";
        }
        elseif ($result == 1){
            echo "Ping unsuccessful! <br/>";
        }    
}
pingAddress("192.168.220.1");
pingAddress("192.168.220.2");

仍然显示成功。我可能在这里做错了什么。有任何想法吗?

4

2 回答 2

1

你需要的是preg_grep。试试这个:

function pingAddress($TEST) {
    $pingresult = exec("ping -n 1 $TEST  && exit", $output, $result);
    //echo $result. "<br/>";

    if (($result == 0)){
        if(count(preg_grep('/Destination host unreachable/i', $output)) == 0){
            echo "Ping successful! <br/>";
        else
            echo "Ping unsuccessful! <br/>";
    }
    elseif ($result == 1){
        echo "Ping unsuccessful! <br/>";
    }    

}

于 2013-03-11T19:19:26.350 回答
0

in_array 将期望整个字符串,即“来自 192.168.200.254 的回复:无法访问目标主机。” . 您可以改用strstr php 手动 strstr php 函数或正则表达式检查。而且由于它在数组中-就像有人建议的那样..加入数组的字符串并尝试查找文本。

于 2013-03-11T19:19:27.950 回答