Networking in C · advanced · ~10 min

UDP server

Bind a UDP socket and receive datagrams.

Lesson

How a UDP server differs from TCP

A UDP server follows the same basic idea as a TCP server, but it is simpler in one key way: there is no listen or accept step.

This is because UDP is connectionless. There is no handshake and no persistent connection between the two sides. Each message (called a datagram) is sent and received on its own.

Receiving a datagram

To read incoming data, you call recvfrom.

  • recvfrom blocks (waits) until a datagram arrives.
  • When one arrives, it copies the data into your buffer.
  • It also fills in the sender's address, so you know who sent the message and can reply to them.

Code examples

int s = socket(AF_INET, SOCK_DGRAM, 0);
bind(s, /* addr */ , sizeof addr);
char buf[1500]; struct sockaddr_in from; socklen_t fl = sizeof from;
ssize_t n = recvfrom(s, buf, sizeof buf, 0, (struct sockaddr*)&from, &fl);

Summary

  • A UDP server skips listen and accept because UDP is connectionless.
  • Each datagram is handled on its own, with no persistent connection.
  • recvfrom blocks until a datagram arrives, then fills in your buffer and the sender's address.

Practice with these exercises