Reputation: 129
I am pinging a couple computers (192.168.200.1 and 192.168.200.2) on my corporate lan that are behind a router (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");
My issue is that is one of these computer is not powered on ( .1 ) and still I get a ping response.
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),
var_dump($output) on 192.168.220.1 ping attempt is showing as:
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),"
}
So I am instead am trying to search the $output array that is created for the false positive "Destination host unreachable" message but not having luck with this route.
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");
Still shows as successful. I am probably doing something wrong here. Any ideas?
Upvotes: 1
Views: 2253
Reputation: 229
in_array will expect the whole string i.e. "Reply from 192.168.200.254: Destination host unreachable." . You can use strstr
php manual strstr php function or regular expression check instead. And since it's in the array - like someone suggested .. join the string of the array and try to find the text.
Upvotes: 0
Reputation: 19888
what you need is preg_grep. Give this a try:
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/>";
}
}
Upvotes: 1