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

2022-08-30 15:48:23

完全披露:这里有一个类似的问题。

有没有办法测试特定端口是否使用PHP正确打开和转发?具体来说,如何使用套接字连接到具有给定端口的给定用户?

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


答案 1

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

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

输出:

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.

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


答案 2
  xxxxx-fpm:
    image: ....
    healthcheck:
      # Check until the FPM port is in in the LISTEN list
      # test: ["CMD-SHELL", "netstat -an | grep -q -F \":9000\""]
      # Or use php to test php since the non alpine fpm image has no binary able to know if a port is in listen mode
      test: ["CMD-SHELL", "php -r '$$c = @fsockopen(\"localhost\", 9000); if (is_resource($$c)) { fwrite(STDOUT, \"OK\"); fclose($$c); exit(0); } else { fwrite(STDERR, \"FAIL\"); exit(1); }'"]
      interval: 2s
      timeout: 3s
      retries: 30
      start_period: 10s

推荐