Function name: socket_bind()
Function Description: The socket_bind() function is used to bind a socket to a specific IP address and port number.
Applicable version: This function is suitable for PHP 4 >= 4.0.5, PHP 5, PHP 7
Syntax: bool socket_bind ( resource $socket , string $address [, int $port = 0 ] )
parameter:
Return value: Return true on success, and false on failure.
Example:
// 创建一个TCP 套接字$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 绑定套接字到IP 地址和端口号$address = '127.0.0.1'; // IP 地址$port = 8080; // 端口号if (socket_bind($socket, $address, $port) === false) { echo "绑定套接字失败: " . socket_strerror(socket_last_error($socket)); exit; } echo "套接字绑定成功!";
The above example demonstrates how to create a TCP socket and bind it to port number 8080 with the local IP address 127.0.0.1. If the binding is successful, "Socket binding is successful!" will be output, otherwise the error message of failed binding will be output.
Please note that in actual use, error handling and exception handling may be required according to specific requirements to ensure the robustness and reliability of the code.