Networking in C · advanced · ~10 min

UDP client

Send a single datagram to a peer.

Lesson

UDP Is Connectionless

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:

  • Create a SOCK_DGRAM socket (a datagram socket).
  • Call sendto(...) to send a message. You pass the destination address every time you send.
  • Call recvfrom(...) to receive a message. It fills in the sender's address for you.

No Delivery Guarantees

UDP does not promise reliable delivery. With UDP, packets may be:

  • Lost — never arrive.
  • Reordered — arrive in a different order than they were sent.
  • Duplicated — arrive more than once.

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).

Code examples

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);

Summary

  • UDP is connectionless: there is no setup step before sending.
  • Use 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.
  • UDP can lose, reorder, or duplicate packets — add retry and sequencing logic yourself if you need reliability.

Practice with these exercises