Function name: socket_last_error()
Function description: socket_last_error() function returns the error code of the last socket operation.
Usage: int socket_last_error ( resource $socket )
parameter:
Return value: Returns an integer value indicating the error code of the last socket operation. If no error occurs, return 0.
Example:
// 创建一个TCP socket $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 连接到远程服务器$result = socket_connect($socket, '127.0.0.1', 80); // 检查连接是否成功if ($result === false) { // 获取最近一次socket 错误码$errorCode = socket_last_error($socket); // 获取错误消息$errorMessage = socket_strerror($errorCode); echo "连接失败,错误码: $errorCode, 错误信息: $errorMessage"; } else { echo "连接成功!"; } // 关闭socket 连接socket_close($socket);
In the example above, we first create a TCP socket and try to connect to the remote server. If the connection fails, we use the socket_last_error() function to get the error code of the last socket operation, and use the socket_strerror() function to get the corresponding error message. If the connection is successful, a message of successful connection is displayed. Finally, we closed the socket connection.
Please note that the socket_last_error() function only returns the error code of the last socket operation. If you need to obtain the error code after multiple socket operations, the function should be called in time after each operation.