2013-03-11 60 views
1

我在我的公司局域網(192.168.200.254)後面ping了幾臺計算機(192.168.200.1和192.168.200.2)。PHP Exec Ping目標主機無法訪問

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($輸出)顯示爲:

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)," 
} 

所以我代替我試圖尋找這是對假陽性「目標創造了$輸出數組主機無法訪問「的消息,但沒有這條路線的運氣。

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

仍然顯示成功。我可能在這裏做錯了事。有任何想法嗎?

+0

in_array將不起作用,因爲它需要匹配元素的整個值。相反,我可能會做一些愚蠢的事情,比如將數組連接到單個字符串中,並將preg_match作爲您正在查找的字符串。或者,如果您認爲這是一個安全的假設,那麼只需在數組的第三個元素上進行preg_match。 – mkaatman 2013-03-11 19:14:41

回答

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

}

+0

工作很好,發現這一點。 – vashavoc 2013-03-11 19:43:50

0

in_array會想到整個字符串即「答覆從192.168.200.254:目標主機不可達」 。您可以使用strstrphp manual strstr php函數或正則表達式檢查代替。並且因爲它在數組中 - 就像有人建議的那樣..加入數組的字符串並嘗試查找文本。