Current Location: Home> Function Categories> socket_create

socket_create

Create sockets (communication endpoint)
Name:socket_create
Category:Sockets
Programming Language:php
One-line Description:Create a socket resource

Function: socket_create()

Applicable version: PHP 4, PHP 5, PHP 7

Usage: The socket_create() function is used to create a socket resource.

Syntax: resource socket_create(int $domain, int $type, int $protocol)

parameter:

  • $domain: Specifies the protocol family of the socket, which can be one of the following constants:
    • AF_INET: IPv4 protocol family
    • AF_INET6: IPv6 protocol family
    • AF_UNIX: Local communication protocol family
  • $type: Specifies the type of the socket, which can be one of the following constants:
    • SOCK_STREAM: Streaming socket, using TCP protocol
    • SOCK_DGRAM: Datagram socket, using UDP protocol
    • SOCK_RAW: Raw socket, can access the underlying protocol
  • $protocol: Specifies the protocol used by the socket, which can be one of the following constants:
    • SOL_TCP: TCP protocol
    • SOL_UDP: UDP protocol
    • SOL_SOCKET: The underlying socket protocol

Return value: Returns a socket resource when successful, and returns false when failure.

Example:

 <?php // 创建一个TCP套接字$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { echo "套接字创建失败: " . socket_strerror(socket_last_error()) . PHP_EOL; } else { echo "套接字创建成功!" . PHP_EOL; // 关闭套接字socket_close($socket); } ?>

In the above example, a TCP socket is created using the socket_create() function, which specifies that the protocol family is IPv4 (AF_INET), the socket type is stream socket (SOCK_STREAM), and the protocol is TCP (SOL_TCP). If the creation is successful, print "Socket creation is successful!", otherwise print the error message that failed to create. Finally, use the socket_close() function to close the socket.

Similar Functions
Popular Articles