如何在 PHP 中 Ping 远程服务器端口?

Mary-Kate Olsen
发布: 2024-10-18 12:09:31
原创
598 人浏览过

How to Ping a Remote Server Port in PHP?

使用 PHP Ping 服务器端口

获取远程服务器的连接状态是网络管理和测试的一个重要方面。 PHP 提供了一种使用 fsockopen() 函数 ping IP 地址和端口的简单方法。但是,问题中提到的现有脚本仅限于测试网站,而不是特定的 IP:端口组合。

为了解决此需求,我们可以利用 TCP 连接建立机制。通过尝试与给定的 IP 地址和端口建立 TCP 连接,我们可以推断服务器的可用性。下面的代码封装了此功能:

<code class="php"><?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"; 
}

// Usage example: ping a server at IP address 127.0.0.1, port 80
echo ping("127.0.0.1", 80, 10);

?></code>
登录后复制

此代码片段确定服务器是否在指定端口上接受 TCP 连接。如果在给定的超时时间内建立了连接,该函数将返回 ping 响应时间(以毫秒为单位);否则,它返回“down”以指示服务器无法访问。

要进一步细化响应,您可以使用接受的答案中提供的 pingDomain() 函数:

<code class="php"><?php

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

// Usage example: ping a server at domain name example.com
echo pingDomain("example.com");

?></code>
登录后复制

通过利用 PHP 的套接字函数,我们可以有效地 ping IP 地址和域名,以测试连接并识别无响应的主机。

以上是如何在 PHP 中 Ping 远程服务器端口?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!