Home

sendto

Sendto is a function in the Berkeley sockets API used to transmit a message to a specific destination address. It is commonly employed with datagram sockets (such as UDP) to send a single datagram to a chosen destination. The call can also be used with raw or connected sockets, but on connected sockets the destination may be ignored by some implementations.

In POSIX systems, the prototype is:

ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t dest_len);

In Windows Sockets, the signature is:

int sendto(SOCKET s, const char *buf, int len, int flags, const struct sockaddr *to, int tolen);

Parameters include the socket descriptor, a buffer with the data to send, the length of the data,

Return value is the number of bytes sent, or -1 on error in POSIX (with errno set).

Usage notes:

- Primarily used with UDP or other connectionless protocols; with UDP, each sendto call specifies the datagram’s

- For connected sockets (via connect), dest_addr may be ignored.

- To send to broadcast or multicast addresses, appropriate socket options (such as SO_BROADCAST) and multicast configurations

Example (POSIX):

struct sockaddr_in dest;

dest.sin_family = AF_INET;

dest.sin_port = htons(12345);

inet_pton(AF_INET, "203.0.113.5", &dest.sin_addr);

sendto(sockfd, "hello", 5, 0, (struct sockaddr *)&dest, sizeof(dest));

See also: send, recvfrom, recv, getsockname.

optional
flags,
and
a
destination
address
structure
(dest_addr)
with
its
length
(dest_len).
The
destination
address
is
typically
a
sockaddr_in
for
IPv4
or
sockaddr_in6
for
IPv6.
On
Windows,
the
function
returns
SOCKET_ERROR
and
extended
error
information
is
retrieved
with
WSAGetLastError.
destination.
may
be
required.