Current Location: Home> Function Categories> socket_getsockname

socket_getsockname

Query the local end of a given socket, which may result in a host/port or Unix file system path, depending on its type
Name:socket_getsockname
Category:Sockets
Programming Language:php
One-line Description:Get the local protocol address of a socket

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:

  • $socket: Required. A valid socket resource.
  • $addr: Required. A variable used to store local protocol addresses. Pass by reference, return the local protocol address.
  • $port: Optional. A variable used to store the local port number. Pass by reference, return the local port number.

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.

Similar Functions
Popular Articles