socket_getpeername
Query the remote end of a given socket, which may result in a host/port or Unix file system path, depending on its type
Function name: socket_getpeername()
Applicable version: PHP 4, PHP 5, PHP 7
Usage: The socket_getpeername() function is used to obtain the IP address and port number of the remote host associated with the socket.
Syntax: bool socket_getpeername ( resource $socket , string &$address [, 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); // 绑定套接字到IP地址和端口socket_bind($socket, '127.0.0.1', 8080); // 监听连接socket_listen($socket); // 接受客户端连接$clientSocket = socket_accept($socket); // 获取客户端的IP地址和端口号if (socket_getpeername($clientSocket, $address, $port)) { echo "客户端IP地址:{$address}\n"; echo "客户端端口号:{$port}\n"; } else { echo "获取远程主机信息失败\n"; } // 关闭套接字socket_close($socket); ?>
In the example above, we create a TCP socket and bind to the local address and port. Then we listen for the connection and accept the client connection. Finally, use the socket_getpeername() function to get the client's IP address and port number and print them out.