2017-07-20 75 views
0

我創建使用UDP套接字:如何在PHP中查找套接字的本地端口?

$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

[插座,PHP,本地端口(可能的重複https://stackoverflow.com/questions/21640660/sockets-php-local-port ) – Dalton

+0

這裏返回的端口總是0,addr是0.0.0.0 – ssk

+1

嗯,是的,你正在創建套接字,但你沒有連接它:'socket_connect($ sock,$ server_ip_here,$ port_here)';之後,它應該返回正確的IP和端口。 – icecub

回答

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()); 
} 
相關問題