使用 PHP 测试端口是否打开并转发

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2226374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:37:25  来源:igfitidea点击:

Test if port open and forwarded using PHP

phpportforwarding

提问by Charlie Salts

Full Disclosure: There's a similar question here.

全面披露:有一个类似的问题在这里

Is there any way I can test if a particular port is open and forwarded properly using PHP? Specifically, how do I go about using a socket to connect to a given user with a given port?

有什么方法可以测试特定端口是否打开并使用 PHP 正确转发?具体来说,我如何使用套接字连接到具有给定端口的给定用户?

An Example of this is in the 'Custom Port Test' section of WhatsMyIP.org/ports.

这方面的一个示例位于WhatsMyIP.org/ports的“自定义端口测试”部分。

回答by Alix Axel

I'm not sure what you mean by being "forwarded properly", but hopefully this example will do the trick:

我不确定你所说的“正确转发”是什么意思,但希望这个例子能解决问题:

$host = 'stackoverflow.com';
$ports = array(21, 25, 80, 81, 110, 443, 3306);

foreach ($ports as $port)
{
    $connection = @fsockopen($host, $port);

    if (is_resource($connection))
    {
        echo '<h2>' . $host . ':' . $port . ' ' . '(' . getservbyport($port, 'tcp') . ') is open.</h2>' . "\n";

        fclose($connection);
    }

    else
    {
        echo '<h2>' . $host . ':' . $port . ' is not responding.</h2>' . "\n";
    }
}

Output:

输出:

stackoverflow.com:21 is not responding.
stackoverflow.com:25 is not responding.
stackoverflow.com:80 (http) is open.
stackoverflow.com:81 is not responding.
stackoverflow.com:110 is not responding.
stackoverflow.com:443 is not responding.
stackoverflow.com:3306 is not responding.


See http://www.iana.org/assignments/port-numbersfor a complete list of port numbers.

有关端口号的完整列表,请参阅http://www.iana.org/assignments/port-numbers