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).
- 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
inet_pton(AF_INET, "203.0.113.5", &dest.sin_addr);
sendto(sockfd, "hello", 5, 0, (struct sockaddr *)&dest, sizeof(dest));