如何使用 PHP Ping 伺服器連接埠:逐步指南

Mary-Kate Olsen
發布: 2024-10-18 10:52:03
原創
657 人瀏覽過

How to Ping a Server Port with PHP: A Step-by-Step Guide

Pinging a Server Port with PHP

As you've correctly noted, the provided PHP script is designed to ping websites by their domain name. To adapt it for pinging specific IP addresses and port numbers, we need to make some adjustments.

The key function you'll need is fsockopen(), which allows you to establish a socket connection to a remote server. By specifying the server's IP address and port number, you can attempt to connect and verify if the server is accepting connections on that specific port.

Here's a revised version of the ping function:

<code class="php">function pingPort($ip, $port, $timeout) 
{ 
  $tB = microtime(true); 
  $fP = fsockopen($ip, $port, $errno, $errstr, $timeout); 
  if (!$fP) { return "down"; } 
  $tA = microtime(true); 
  return round((($tA - $tB) * 1000), 0)." ms"; 
}</code>
登入後複製

This function takes three arguments:

  • $ip: The IP address of the server you want to ping
  • $port: The port number you want to ping
  • $timeout: The amount of time (in seconds) to wait for a response before giving up

If the connection can be established, the function will return the round-trip time in milliseconds. Otherwise, it will return "down" to indicate that the port is not reachable.

To use the function, you can simply call it like this:

<code class="php">$ip = "192.168.1.100";
$port = 80;
$timeout = 10;

$ping = pingPort($ip, $port, $timeout);

if ($ping == "down") {
  echo "Port $port is not reachable on $ip.";
} else {
  echo "Ping to $ip:$port: $ping ms";
}</code>
登入後複製

This script will display the ping time if the port is reachable, or it will output an error message if the connection attempt fails.

以上是如何使用 PHP Ping 伺服器連接埠:逐步指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!