Function: stream_socket_get_name()
Applicable version: PHP 4 >= 4.3.0, PHP 5, PHP 7
Usage: string stream_socket_get_name ( resource $handle , bool $want_peer )
parameter:
Return value: Returns the name of the specified socket, and returns false if it fails.
Example:
// 创建一个TCP 套接字连接到example.com 的80 端口$socket = stream_socket_client("tcp://example.com:80", $errno, $errstr, 30); if ($socket) { // 获取本地套接字名称$localName = stream_socket_get_name($socket, false); echo "本地套接字名称: " . $localName . PHP_EOL; // 获取对方套接字名称$peerName = stream_socket_get_name($socket, true); echo "对方套接字名称: " . $peerName . PHP_EOL; // 关闭套接字连接fclose($socket); } else { echo "连接失败: " . $errstr . " (" . $errno . ")"; }
Output:
本地套接字名称: tcp://192.168.1.100:12345对方套接字名称: tcp://93.184.216.34:80
The above example demonstrates how to use the stream_socket_get_name() function to get the local socket name and the other socket name. First, we use the stream_socket_client() function to create a TCP socket to connect to port 80 of example.com. Then, we use the stream_socket_get_name() function to obtain the local socket name and the other socket name respectively. Finally, we closed the socket connection.
Note that the local socket name is a string starting with "tcp://", followed by the IP address and port number. The other party's socket name is also a string starting with "tcp://", followed by the other party's IP address and port number.