代码之家  ›  专栏  ›  技术社区  ›  vashavoc

无法访问PHP执行Ping目标主机

  •  1
  • vashavoc  · 技术社区  · 11 年前

    我正在我的公司局域网上ping路由器(192.168.200.254)后面的几台计算机(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上的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)," 
    }
    

    因此,我正试图搜索为假阳性“Destination host unareachable”消息创建的$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 回复  |  直到 11 年前
        1
  •  1
  •   DiverseAndRemote.com    11 年前

    你需要的是 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/>";
        }    
    

    }

        2
  •  0
  •   V_K    11 年前

    in_array需要完整的字符串,即“Reply from 192.168.200.254:Destination host unreachable”。您可以使用 strstr php manual strstr php函数或正则表达式检查。既然它在数组中——就像有人建议的那样。。连接数组的字符串并尝试查找文本。