Function name: socket_getsockname()
Applicable version: PHP 4 >= 4.1.0, PHP 5, PHP 7
Function description: socket_getsockname() function is used to obtain the local protocol address of a socket.
Syntax: bool socket_getsockname ( resource $socket , string &$addr [, int &$port ] )
parameter:
Return value: Return true on success, and false on failure.
Example:
<?php // 创建一个TCP套接字$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 绑定套接字到本地地址和端口socket_bind($socket, '127.0.0.1', 8080); // 获取本地地址和端口if (socket_getsockname($socket, $addr, $port)) { echo "本地协议地址:$addr\n"; echo "本地端口号:$port\n"; } else { echo "获取本地地址和端口失败\n"; } // 关闭套接字socket_close($socket); ?>
Output result:
本地协议地址:127.0.0.1本地端口号:8080
The above example demonstrates how to use the socket_getsockname() function to get the socket's local protocol address and port number. First, create a TCP socket and bind it to the local address and port via the socket_bind() function. Then, use the socket_getsockname() function to get the socket's local protocol address and port number and store it in the corresponding variable. Finally, the local protocol address and port number are output to the screen through the echo statement.
Please note that the socket creation, binding and closing operations in the example are only used to demonstrate how to use the socket_getsockname() function, and may need to be adjusted according to specific needs when using it.