开发者

Test if port open and forwarded using PHP

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 s开发者_如何学Pythonocket to connect to a given user with a given port?

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


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-numbers for a complete list of port numbers.


  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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜