【问题标题】:How to find the local port of a socket in PHP?如何在 PHP 中找到套接字的本地端口?
【发布时间】:2017-07-20 23:30:50
【问题描述】:

我正在使用以下方法创建 UDP 套接字:

$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);

当我使用 socket_getsockname 获取套接字名称时:

   /**
    * Get Source port (Refactored to allow unit testing)
    *
    * @return string
    */
    private static function getSourcePort($sock)
    {
        $addr = null;
        $port = null;
        socket_getsockname($sock, $addr, $port);
        return $port;
    }

返回的端口始终为 0,地址为 0.0.0.0

如何正确获取绑定端口?

【问题讨论】:

  • Sockets, PHP, local port的可能重复
  • 这里返回的端口始终为0,地址为0.0.0.0
  • 嗯,是的,你正在创建套接字,但你没有连接它:socket_connect($sock, $server_ip_here, $port_here);之后它应该返回正确的 ip 和端口。

标签: php sockets udp port


【解决方案1】:

在创建后绑定套接字解决了这个问题:

if (socket_bind($sock, $sourceIp) === false)
{
    $failReason = "socket_bind() failed: reason: " . socket_strerror(socket_last_error());
}

// get the source port
$sourcePort = 0;
if (socket_getsockname($sock, $sourceIp, $sourcePort) === false)
{
    $failReason = "socket_getsockname() failed: reason: " . socket_strerror(socket_last_error());
}

【讨论】:

    猜你喜欢
    • 2014-03-05
    • 2011-10-03
    • 2012-06-12
    • 1970-01-01
    • 2011-06-14
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 2010-10-23
    相关资源
    最近更新 更多