函數:
<?php
function ping($ip, $times=4){$info = array();
if (!is_numeric($times) || $times-4<0) {
$times = 4;
}
if (PATH_SEPARATOR==':' || DIRECTORY_SEPARATOR=='/') { //linux
exec("ping $ip -c $times", $info);
if (count($info) < 9) {
$info['error'] = 'timeout';
}
} else { //windows
exec("ping $ip -n $times", $info);
if (count($info) < 10) {
$info['error'] = 'timeout';
}
}
return $info;
}
$ip = '127.0.0.1';
print_r(ping($ip));
?>
成功:
Array
(
[0] => PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
[1] => 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.052 ms
[2] => 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.055 ms
[3] => 64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.039 ms
[4] => 64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.046 ms
[5] =>
[6] => --- 127.0.0.1 ping statistics ---
[7] => 4 packets transmitted, 4 received, 0% packet loss, time 3000ms
[8] => rtt min/avg/max/mdev = 0.039/0.048/0.055/0.006 ms
)
[Finished in 3.1s]
失敗:
Array
(
[0] => PING 192.168.10.198 (192.168.10.198) 56(84) bytes of data.
[1] => From 192.168.10.195 icmp_seq=1 Destination Host Unreachable
[2] => From 192.168.10.195 icmp_seq=2 Destination Host Unreachable
[3] => From 192.168.10.195 icmp_seq=3 Destination Host Unreachable
[4] => From 192.168.10.195 icmp_seq=4 Destination Host Unreachable
[5] =>
[6] => --- 192.168.10.198 ping statistics ---
[7] => 4 packets transmitted, 0 received, +4 errors, 100% packet loss, time 6001ms
[8] => pipe 4
)
[Finished in 6.0s]