Current Location: Home> Function Categories> socket_sendto

socket_sendto

Send a message to the socket, whether it is connected or not
Name:socket_sendto
Category:Sockets
Programming Language:php
One-line Description:Send data to the specified remote address

Function name: socket_sendto()

Applicable version: PHP 4 >= 4.1.0, PHP 5, PHP 7

Usage: socket_sendto(resource $socket, string $data, int $length, int $flags, string $address [, int $port = 0]) : int|false

Description: The socket_sendto() function is used to send data to the specified remote address.

parameter:

  • $socket: Required, a valid socket resource created by socket_create().
  • $data: Required, data to be sent.
  • $length: Required, length of data to be sent.
  • $flags: Optional, flags that can be used to adjust the sending behavior, default to 0.
  • $address: Required, destination address.
  • $port: optional, target port, default is 0.

Return value:

  • If data is sent successfully, the number of bytes sent is returned.
  • If an error occurs, false is returned and the error code can be obtained by calling socket_last_error().

Example:

 // 创建套接字$socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); // 目标地址和端口$address = '127.0.0.1'; $port = 1234; // 要发送的数据$data = 'Hello, server!'; // 发送数据到指定地址if (socket_sendto($socket, $data, strlen($data), 0, $address, $port) === false) { echo "发送数据失败: " . socket_strerror(socket_last_error()) . "\n"; } else { echo "成功发送了" . strlen($data) . " 字节的数据到$address:$port\n"; } // 关闭套接字socket_close($socket);

Notes:

  • Before using the socket_sendto() function, you must create a socket via socket_create().
  • Make sure to pass the correct destination address and port to ensure that the data is sent to the correct destination.
  • If the sending fails, you can get the error code by calling socket_last_error() and use socket_strerror() to convert the error code into readable error information.
  • After sending, the socket should be closed using socket_close() to free up the resource.
Similar Functions
Popular Articles