Networking in C · advanced · ~10 min
Bind a UDP socket and receive datagrams.
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.
To read incoming data, you call recvfrom.
recvfrom blocks (waits) until a datagram arrives.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);
listen and accept because UDP is connectionless.recvfrom blocks until a datagram arrives, then fills in your buffer and the sender's address.