Networking in C · advanced · ~10 min
Send a single datagram to a peer.
UDP (User Datagram Protocol) does not set up a connection before sending data. Each message, called a datagram, is sent on its own.
Because there is no connection, the steps are simple:
SOCK_DGRAM socket (a datagram socket).sendto(...) to send a message. You pass the destination address every time you send.recvfrom(...) to receive a message. It fills in the sender's address for you.UDP does not promise reliable delivery. With UDP, packets may be:
If your application needs reliability, you must add it yourself. Common additions include retransmission (retrying lost messages) and sequence numbers (to detect order and duplicates).
int s = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in a = {0};
a.sin_family = AF_INET; a.sin_port = htons(53);
inet_pton(AF_INET, "127.0.0.1", &a.sin_addr);
sendto(s, "hi", 2, 0, (struct sockaddr*)&a, sizeof a);
SOCK_DGRAM socket; send with sendto and receive with recvfrom.sendto takes the destination address on every call; recvfrom reports the sender's address.