如何在PHP中找到套接字的本地端口?

时间:2017-07-20 23:30:50

标签: php sockets udp port

我使用以下方法创建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

如何正确获取绑定端口?

1 个答案:

答案 0 :(得分: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());
}