Function name: socket_recvfrom()
Applicable version: PHP 4 >= 4.1.0, PHP 5, PHP 7
Function description: The socket_recvfrom() function receives data from the specified socket and stores the sender's address and port in the specified variable.
Syntax: int socket_recvfrom ( resource $socket , string &$buf , int $len , int $flags , string &$name [, int &$port ] )
Parameter description:
Return value: Returns the number of bytes received when successful, and returns FALSE when failure.
Sample code:
$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); if ($socket === false) { echo "socket_create() failed: " . socket_strerror(socket_last_error()) . "\n"; exit; } $bind = socket_bind($socket, '0.0.0.0', 8888); if ($bind === false) { echo "socket_bind() failed: " . socket_strerror(socket_last_error($socket)) . "\n"; exit; } $buffer = ''; $senderAddress = ''; $senderPort = 0; // 接收数据并获取发送方的地址和端口$bytes = socket_recvfrom($socket, $buffer, 1024, 0, $senderAddress, $senderPort); if ($bytes === false) { echo "socket_recvfrom() failed: " . socket_strerror(socket_last_error($socket)) . "\n"; exit; } echo "Received $bytes bytes from $senderAddress:$senderPort\n"; echo "Data: $buffer\n"; socket_close($socket);
The above sample code creates a UDP socket and binds to the local port 8888. Then use the socket_recvfrom() function to receive the data, and store the sender's address and port in the corresponding variable. Finally, output the received data, the sender's address and port, and close the socket.
Note: The example is using UDP sockets. If you need to use TCP sockets, you need to use the socket_recv() function to receive data.