Current Location: Home> Function Categories> socket_getpeername

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
Name:socket_getpeername
Category:Sockets
Programming Language:php
One-line Description:Get the IP address and port number of the remote host associated with the socket

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:

  • $socket: Required. A valid socket resource returned by socket_create() or socket_accept().
  • $address: Required. Used to store the IP address of the remote host.
  • $port: optional. The port number used to store the remote host.

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.

Similar Functions
Popular Articles