我使用以下方法创建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
如何正确获取绑定端口?
答案 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());
}