gpt4 book ai didi

php - 如何使用 PHP ping 服务器端口?

转载 作者:IT王子 更新时间:2023-10-29 00:55:42 24 4
gpt4 key购买 nike

我想要一个 PHP 脚本,它允许您 ping 一个 IP 地址和一个端口号 (ip:port)。我找到了一个类似的脚本,但它只适用于网站,不适用于 ip:port

<?php

function ping($host, $port, $timeout)
{
$tB = microtime(true);
$fP = fSockOpen($host, $port, $errno, $errstr, $timeout);
if (!$fP) { return "down"; }
$tA = microtime(true);
return round((($tA - $tB) * 1000), 0)." ms";
}

//Echoing it will display the ping if the host is up, if not it'll say "down".
echo ping("www.google.com", 80, 10);

?>

我想要这个用于游戏服务器。

我的想法是,我可以输入 IP 地址和端口号,然后得到 ping 响应。

最佳答案

我认为 this question 的答案几乎总结了你的问题。

If what you want to do is find out whether a given host will accept TCP connections on port 80, you can do this:

$host = '193.33.186.70'; 
$port = 80;
$waitTimeoutInSeconds = 1;
if($fp = fsockopen($host,$port,$errCode,$errStr,$waitTimeoutInSeconds)){
// It worked
} else {
// It didn't work
}
fclose($fp);

For anything other than TCP it will be more difficult (although since you specify 80, I guess you are looking for an active HTTP server, so TCP is what you want). TCP is sequenced and acknowledged, so you will implicitly receive a returned packet when a connection is successfully made. Most other transport protocols (commonly UDP, but others as well) do not behave in this manner, and datagrams will not be acknowledged unless the overlayed Application Layer protocol implements it.

The fact that you are asking this question in this manner tells me you have a fundamental gap in your knowledge on Transport Layer protocols. You should read up on ICMP and TCP, as well as the OSI Model.

另外,这里有一个 slightly cleaner ping 主机的版本。

// Function to check response time
function pingDomain($domain){
$starttime = microtime(true);
$file = fsockopen ($domain, 80, $errno, $errstr, 10);
$stoptime = microtime(true);
$status = 0;

if (!$file) $status = -1; // Site is down
else {
fclose($file);
$status = ($stoptime - $starttime) * 1000;
$status = floor($status);
}
return $status;
}

关于php - 如何使用 PHP ping 服务器端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9841635/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com