任何人都知道在php中ping一个IP地址的简单干净方法,只回显平均ping时间的结果?
例如,当我真正想要的是“35”时,我会得到“最小值= 35毫秒,最大值= 35毫秒,平均值= 35毫秒”
感谢。
答案 0 :(得分:5)
您可以使用exec()
- 函数执行shell命令ping
,如下例所示:
<?php
function GetPing($ip=NULL) {
if(empty($ip)) {$ip = $_SERVER['REMOTE_ADDR'];}
if(getenv("OS")=="Windows_NT") {
$ping=explode(",", $exec);
return $ping[1];//Maximum = 78ms
}
else {
$exec = exec("ping -c 3 -s 64 -t 64 ".$ip);
$array = explode("/", end(explode("=", $exec )) );
return ceil($array[1]) . 'ms';
}
}
echo GetPing();
?>
答案 1 :(得分:5)
我猜你想要的是这个:
const PING_REGEX_TIME = '/time(=|<)(.*)ms/';
const PING_TIMEOUT = 10;
const PING_COUNT = 1;
$os = strtoupper(substr(PHP_OS, 0, 3));
$url = 'www.google.com';
// prepare command
$cmd = sprintf('ping -w %d -%s %d %s',
PING_TIMEOUT,
$os === 'WIN' ? 'n' : 'c',
PING_COUNT,
escapeshellarg($url)
);
exec($cmd, $output, $result);
if (0 !== $result) {
// something went wrong
}
$pingResults = preg_grep(PING_REGEX_TIME, $output); // discard output lines we don't need
$pingResult = array_shift($pingResults); // we wanted just one ping anyway
if (!empty($pingResult)) {
preg_match(PING_REGEX_TIME, $pingResult, $matches); // we get what we want here
$ping = floatval(trim($matches[2])); // here's our time
} else {
// something went wrong (mangled output)
}
这是一个从单个ping中获取ms的示例,但很容易调整它以获得您想要的任何内容。您所要做的就是使用正则表达式,超时和计数常量。
您可能还希望根据操作系统调整正则表达式(或添加更多),因为Linux ping将提供来自Windows的不同格式的结果。
答案 2 :(得分:4)
暂时在线发现这个功能,对不起,我不记得在哪里可以信用,但你可以用for-loop来获得平均值:
function ping($host, $timeout = 10)
{
$output = array();
$com = 'ping -n -w ' . $timeout . ' -c 1 ' . escapeshellarg($host);
$exitcode = 0;
exec($com, $output, $exitcode);
if ($exitcode == 0 || $exitcode == 1)
{
foreach($output as $cline)
{
if (strpos($cline, ' bytes from ') !== FALSE)
{
$out = (int)ceil(floatval(substr($cline, strpos($cline, 'time=') + 5)));
return $out;
}
}
}
return FALSE;
}
$total = 0;
for ($i = 0; $i<=9; $i++)
{
$total += ping('www.google.com');
}
echo $total/10;
只需根据需要更改for循环中的次数。