PHP Exec Ping目标主机无法访问

时间:2013-03-11 19:10:11

标签: php exec ping router

我正在公司局域网上ping几台计算机(192.168.200.1和192.168.200.2),它们位于路由器后面(192.168.200.254)。

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上的

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

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

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

2 个答案:

答案 0 :(得分: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/>";
    }    

}

答案 1 :(得分:0)

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