如何使用PHP ping服务器端口? [英] How can I ping a server port with PHP?

查看:144
本文介绍了如何使用PHP ping服务器端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want a PHP script which allows you to ping an IP address and a port number (ip:port). I found a similar script but it works only for websites, not 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);

?>

我想要一个游戏服务器.

I want this for a game server.

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

The idea is that I can type in the IP address and port number, and I get the ping response.

推荐答案

我认为

I think the answer to this question pretty much sums up the problem with your question.

如果您要确定给定的主机是否接受 端口80上的TCP连接,您可以执行以下操作:

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);

对于TCP以外的其他任何东西都会更加困难(尽管 您指定80,我想您正在寻找活动的HTTP服务器,因此 TCP是您想要的). TCP已排序并得到确认,因此您将 连接成功时隐式接收返回的数据包 制成.大多数其他传输协议(通常为UDP,但其他协议为 好)不要以这种方式表现,并且数据报也不会 确认,除非覆盖了应用层协议 实现它.

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.

您以这种方式问这个问题的事实告诉我您 您对传输层协议的了解方面存在根本性的差距. 您应该在 ICMP OSI模型.

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.

此外,这是一个

Also, here's a slightly cleaner version to ping to hosts.

// 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 ping服务器端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆