【问题标题】:Test if port open and forwarded using PHP测试端口是否打开并使用 PHP 转发
【发布时间】:2011-01-14 15:28:35
【问题描述】:

完全披露:有一个类似的问题here

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

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

【问题讨论】:

    标签: php portforwarding


    【解决方案1】:
      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
    

    【讨论】:

      【解决方案2】:

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

      $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

      【讨论】:

      • 谢谢 - 这与我期望的非常相似。当我说“正确转发”时,我的意思是用户在他们的路由器上为我希望使用的端口启用了端口转发。我有一个多人游戏,可以选择充当服务器。因此,需要端口转发,我们希望有一个简单的功能来尝试验证端口实际上是否已转发。
      • 我认为这会测试您的出站和入站接收器是否正确,所以如果您想编写一个函数来测试您的出站,您需要找到一个所有入站端口都打开的公共服务器?
      • 很棒的解决方案。 (y)
      • 这很完美,为我创造了奇迹,并取代了我几乎无法使用的 cURL 解决方案。宝石!
      • 设置超时也很有用$connection = @fsockopen($host, $port, $errno, $errstr, 30);php.net/fsockopen
      猜你喜欢
      • 1970-01-01
      • 2011-10-02
      • 2011-06-22
      • 2012-03-25
      • 2012-02-12
      • 2020-02-07
      • 1970-01-01
      • 2012-08-03
      相关资源
      最近更新 更多