首頁 > 後端開發 > php教程 > 如何使用 PHP Ping 伺服器連接埠?

如何使用 PHP Ping 伺服器連接埠?

Linda Hamilton
發布: 2024-10-18 11:03:02
原創
1263 人瀏覽過

How to Ping a Server Port with PHP?

Pinging a Server Port with PHP

In PHP, you can utilize the fsockopen() function to check whether a server accepts TCP connections on a specified port. Here's how:

$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);
登入後複製

This script will determine if the server at the given IP address is accepting HTTP connections on port 80.

Note: This approach is specific to TCP connections. Other protocols like UDP have different characteristics that require more complex pinging mechanisms.

Customized Pinging

If you require more specific pinging capabilities, consider the following script:

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;
}
登入後複製

This script provides a ping response in milliseconds, indicating the server's latency. You can use this script to monitor game server availability and response times.

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

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板