一直需要用PHP进行ping来检查主机的运行状态,没有实现。(需要主机有某些特定功能模块开启才可以。)
后来发现有大神使用模拟的方式来实现检查,代码不错,主机通用。就拿来简单改了改。
这个代码就是php访问主机的web服务,根据响应模拟ping服务。
/*
* @author lwl887
* @date 20150705
* @email lwl887@163.com
* @function 根据服务器web端口模拟ping的php函数
*
*/
error_reporting(E_ERROR);
header("content-Type: text/html; charset=utf-8");
set_time_limit(600);
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function ping($host,$port)
{
$time_start = microtime_float();
$ip = gethostbyname($host);
$fp = @fsockopen($host,$port,&$errno,&$errstr,1);
if(!$fp) return 'IP: '.$ip.' timed out.
';
$get = "GET / HTTP/1.1\r\nHost:".$host."\r\nConnection: Close\r\n\r\n";
@fputs($fp,$get);
@fclose($fp);
$time_end = microtime_float();
$time = $time_end - $time_start;
$time = ceil($time * 1000);
return 'IP: '.$ip.' time='.$time.'ms
';
}
function check($hostname,$hostIP,$hostport='80')
{
echo $hostname.' ';
echo ping($hostIP,$hostport);
}
$t=time();
echo date("Y-m-d H:i:s",$t);
check('服务器','192.168.1.10');
check('虚拟机','192.168.9.10');
check('总变录像机','192.168.168.11');
check('2线录像机','192.168.168.12');
check('3线录像机','192.168.168.13');
check('4线录像机','192.168.168.14');
check('实验线录像机','192.168.168.15');
for($i = 16;$i < 195;$i++)
{
$p='192.168.168.'.$i ;
check(' ',$p);
}
$t=time();
echo date("Y-m-d H:i:s",$t);
?>