一直需要用PHP進行ping來檢查主機的運作狀态,沒有實作。(需要主機有某些特定功能子產品開啟才可以。)
後來發現有大神使用模拟的方式來實作檢查,代碼不錯,主機通用。就拿來簡單改了改。
這個代碼就是php通路主機的web服務,根據響應模拟ping服務。
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);
?>