PHP 使用 ping 命令ping ip

通过下面的代码在php运行,可以实现让服务器ping到指定ip的接通性和连接率

演示地址:http://ip.429006.com/ping.php

演示效果:从ip.429006.com到8.8.8.8之间的延时是1ms

其实很简单,ping的代码如下:

<?php
/**
*@param $ip target ip
*@param $times ping times
*/
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 = '8.8.8.8';//IP地址
print_r(ping($ip));
?>

结果如下:

Array (
[0] =>
[1] => Pinging 8.8.8.8 with 32 bytes of data:
[2] => Reply from 8.8.8.8: bytes=32 time=1ms TTL=54
[3] => Reply from 8.8.8.8: bytes=32 time=1ms TTL=54
[4] => Reply from 8.8.8.8: bytes=32 time=1ms TTL=54
[5] => Reply from 8.8.8.8: bytes=32 time=1ms TTL=54
[6] =>
[7] => Ping statistics for 8.8.8.8:
[8] => Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
[9] => Approximate round trip times in milli-seconds:
[10] => Minimum = 1ms, Maximum = 1ms, Average = 1ms )

原文地址:
https://my.oschina.net/ososchina/blog/345401

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.