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?
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());
}