Current Location: Home> Function Categories> socket_recvfrom

socket_recvfrom

Receive data from a socket, whether it is connection oriented or not
Name:socket_recvfrom
Category:Sockets
Programming Language:php
One-line Description:Receive data from the specified socket and store the sender's address and port in the specified variable

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:

  • $socket: Required, specified socket resource.
  • $buf: Required, variable used to store received data.
  • $len: Required, specifying the maximum number of bytes to be received.
  • $flags: Optional, specify the flag for receiving data, default is 0.
  • $name: Required, variable used to store the sender's address.
  • $port: Optional, used to store the sender's port variable, default is 0.

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.

Similar Functions
Popular Articles