Write a UDP Server and Client in C with sendto
Write a UDP server and client in C with sendto and recvfrom on Linux, and learn why datagrams keep their boundaries but can be lost.

UDP is the other transport you will meet on day one. It has no connection, no handshake and no retransmission. You hand the kernel one message with sendto, and the kernel tries to deliver it as one datagram. This post builds a UDP server and a matching client in C on Linux 6.12 with glibc 2.40, shows how recvfrom tells you who sent each datagram, and explains the guarantees UDP does and does not give you.
The calls are documented in the sendto(2) and recvfrom(2) man pages, and the protocol is defined in RFC 768.
How UDP differs from TCP in code
The program structure changes in four ways:
The socket type is
SOCK_DGRAMinstead ofSOCK_STREAM.A server calls
bindbut neverlistenoraccept, because there are no connections to queue.Each
sendtocarries the destination address, and eachrecvfromreturns the sender's address.One
recvfromreturns exactly one datagram. Message boundaries are preserved, which TCP does not do.
That last point removes a whole class of framing work. If the client sends 12 bytes, the server's recvfrom returns those 12 bytes in one call. There is one catch: if your buffer is smaller than the datagram, the extra bytes are silently discarded and the call still succeeds, so size the buffer for the largest message your protocol allows.
What UDP does not promise
UDP gives you three things and takes away the rest. It keeps message boundaries, it checks a checksum so corrupted datagrams are dropped, and it adds port numbers. It does not promise delivery, order or uniqueness. A datagram may vanish, arrive twice or arrive after a later one. On a loopback test everything looks perfect, which is misleading. A real protocol built on UDP must add its own sequence numbers, acknowledgements or tolerance for loss. Choose UDP when a late packet is worthless, such as a game position update or a name lookup, and when you prefer a retry timer of your own design to the one TCP imposes.
The server
The server creates a datagram socket, binds it to a port and loops. recvfrom fills a sockaddr_in with the sender's address, and the server reuses that structure as the destination in sendto to reply:
#define _DEFAULT_SOURCE
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
int main(void)
{
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) { perror("socket"); return EXIT_FAILURE; }
struct sockaddr_in addr = {0};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(9090);
if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) {
perror("bind");
return EXIT_FAILURE;
}
printf("udp server on port 9090\n");
char buf[1500];
for (;;) {
struct sockaddr_in peer;
socklen_t plen = sizeof peer;
ssize_t n = recvfrom(fd, buf, sizeof buf, 0,
(struct sockaddr *)&peer, &plen);
if (n < 0) {
perror("recvfrom");
continue;
}
char text[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &peer.sin_addr, text, sizeof text);
printf("got %zd bytes from %s:%u\n", n, text,
(unsigned)ntohs(peer.sin_port));
if (sendto(fd, buf, (size_t)n, 0,
(struct sockaddr *)&peer, plen) < 0)
perror("sendto");
}
}The buffer holds 1500 bytes, the usual Ethernet payload limit. UDP over IPv4 can carry up to 65507 bytes of payload, but a datagram larger than the path MTU is fragmented, and losing one fragment loses the whole datagram, so protocols usually keep messages under about one MTU.
The client
The client does not bind. The first sendto makes the kernel assign a local port, and replies come back to it. A receive timeout protects the client from waiting forever if the datagram or the reply was lost, which on UDP is a normal event:
#define _DEFAULT_SOURCE
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
int main(void)
{
int fd = socket(AF_INET, SOCK_DGRAM, 0);
if (fd < 0) { perror("socket"); return EXIT_FAILURE; }
struct timeval tv = { .tv_sec = 2, .tv_usec = 0 };
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
struct sockaddr_in server = {0};
server.sin_family = AF_INET;
server.sin_port = htons(9090);
inet_pton(AF_INET, "127.0.0.1", &server.sin_addr);
const char *msg = "ping";
if (sendto(fd, msg, strlen(msg), 0,
(struct sockaddr *)&server, sizeof server) < 0) {
perror("sendto");
return EXIT_FAILURE;
}
char buf[1500];
ssize_t n = recvfrom(fd, buf, sizeof buf, 0, NULL, NULL);
if (n < 0) {
perror("recvfrom");
close(fd);
return EXIT_FAILURE;
}
printf("reply: %.*s\n", (int)n, buf);
close(fd);
return EXIT_SUCCESS;
}Compile both with gcc -std=c11 -Wall -Wextra -o udp_server udp_server.c and the same for the client. Start the server, then run the client. The client prints:
reply: pingand the server prints a line such as this, with a different client port each run:
udp server on port 9090
got 4 bytes from 127.0.0.1:44219If no server is running, the client's sendto still succeeds, because UDP does not check that anyone is listening. On Linux the kernel may report the resulting ICMP "port unreachable" error on a later call. For an unconnected socket that error is normally not delivered at all, so the client waits for the full two seconds and then recvfrom fails with EAGAIN, printed as Resource temporarily unavailable.
Connected UDP sockets
A UDP socket can call connect. Nothing goes on the wire. The kernel just stores the peer address, so you can use send and recv, and datagrams from other sources are dropped. It also lets the kernel report ICMP errors, so a send to a closed port makes a later recv fail with ECONNREFUSED. That is a convenient way to detect a dead server, and it is the reason many UDP clients connect their sockets.
Common mistakes
The mistakes below come up often when beginners move from TCP to UDP:
Assuming delivery. Always plan for loss with a timeout and a retry.
Using a buffer smaller than the datagram, which truncates the message without an error. Pass
MSG_TRUNCtorecvfromto learn the real length on Linux.Reusing the
socklen_tvalue without resetting it. Set it tosizeof peerbefore everyrecvfrom, because the call overwrites it.Sending very large datagrams, which fragment and become far more likely to be lost.
Treating the sender address as authenticated. UDP source addresses can be forged, so never trust them for security decisions.
Adding a simple retry
Because loss is normal, a client that needs an answer must be ready to ask again. The smallest sound pattern is a loop with a fixed number of attempts. Send the request, wait for a reply up to the receive timeout, and if recvfrom fails with EAGAIN or EWOULDBLOCK, send the same request again. After the last attempt, give up and report the failure to the caller. Both names for the error can be the same value on Linux, but POSIX allows them to differ, so test for both.
Retrying introduces a second problem: duplicates. If the reply was lost and not the request, the server handles the same request twice. For a harmless request such as an echo this does not matter. For anything that changes state, the protocol needs a request identifier so the server can recognise a repeat and answer from memory instead of acting again. This is the first step toward the reliability that TCP gives for free, and it is why people who need ordered, reliable delivery usually choose TCP instead of rebuilding it.
Seeing the sender, and replying to the right place
The server replies with the same sockaddr_in that recvfrom filled in, and that is the whole trick to serving many clients from one socket. There is no per-client state in the kernel. Each datagram arrives with its source address attached, and your program decides what to do with it. If you want to treat a series of datagrams from one peer as a conversation, you keep a table keyed by the peer's address and port in your own code.
This also means the server is cheap. It holds one descriptor whether ten clients or ten thousand are sending, and it never blocks on a slow client, because a reply is a single call that returns once the kernel has queued the datagram. The cost is that all the work of tracking sessions, ordering and timeouts moves into your program. The receive buffer is shared by every client, so a burst of datagrams can overflow it and the kernel drops the excess silently. You can raise the limit with SO_RCVBUF, but the better fix is usually to read faster.
Trying it from the shell
You can test the server without the client program. The nc tool can send one datagram: printf 'ping' | nc -u -w1 127.0.0.1 9090 sends the four bytes and waits a second for a reply. To watch the traffic on the loopback interface, run tcpdump -n -i lo udp port 9090 as root. You will see one packet to port 9090 and one back, with no handshake before them and no close after. Comparing that quiet exchange with the capture of a TCP connection is a good way to see what the connection setup in TCP is paying for.

