duanhe2027
2017-07-20 23:30
浏览 99
已采纳

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

I am creating a UDP socket using:

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

When I use socket_getsockname to get the socket name:

   /**
    * 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;
    }

The port returned is always 0 and the addr is 0.0.0.0

How to get the bound port properly?

图片转代码服务由CSDN问答提供 功能建议

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

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

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

  / ** 
 *获取源端口(重构为允许单元测试)
 * 
 * @return string 
 * / 
私有静态函数getSourcePort($ sock)
 {
 $ addr = null;  
 $ port = null; 
 socket_getsockname($ sock,$ addr,$ port); 
返回$ port; 
} 
   
 
 

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

如何正确获取绑定端口? < / DIV>

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doubinchou4219 2017-07-21 02:55
    已采纳

    Binding the socket after creation fixed the issue:

    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());
    }
    
    打赏 评论

相关推荐 更多相似问题