欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

php做Ping的IP和端口测试

程序员文章站 2024-04-05 19:16:00
...
因为朋友说端口连接不上,特意试了一下用php做Ping测试,结果还是挺满意的。

代码和运行图如下:(如果有大神改进就更好了)

$host = 'www.php100.com';

$port = '80';

$num = 3; //Ping次数

//获取时间

function mt_f (){

list($usec,$sec) = explode(" ",microtime());

return ((float)$usec + (float)$sec); //微秒加秒

}

function ping_f($host,$port){

$time_s = mt_f();

$ip = gethostbyname($host);

$fp = @fsockopen($host,$port);

if(!$fp)

return 'reply time out!';

$get = "GET / HTTP/1.1\r\nHost:".$host."\r\nConnect:".$port."Close\r\n";

fputs($fp,$get);

fclose($fp);

$time_e = mt_f();

$time = $time_e - $time_s;

$time = ceil($time * 1000);

return 'reply from '.$ip.':'.$port.' time = '.$time.'ms
';

}

echo 'ping to '.$host.' ['.gethostbyname($host).'] with port:'.$port.' of data:
';

for($i = 0;$i

echo ping_f($host,$port);

//每次运行中间间隔1S

sleep(1);

//刷新输出缓存

ob_flush();

flush();

}

?>