Lesson 11 of 18 Client-Server Programs

UDP Datagram Sockets in C

A complete UDP example in C: a dual-stack receiver with recvfrom() and a sender with sendto(), plus packet loss, ordering and connected UDP sockets.

40-50 min intermediate 0/18 lessons done
Course contents Lesson 11 of 18 · 0 done
On this page (10 sections)
  1. What you will build
  2. The receiver
  3. The sender
  4. Run it
  5. What UDP doesn’t do for you
  6. Connected UDP sockets
  7. When to choose UDP
  8. Key takeaways
  9. Exercises
  10. Quiz

What you will build

A sensor network in miniature. Small programs (sensor_send) report readings like kitchen 21.5 over UDP; a collector (sensor_listen) prints each reading and who sent it. No connections, no handshakes, one packet per reading.

The receiver

/* sensor_listen.c - receive UDP sensor readings and print who sent them.
 * Usage: ./sensor_listen 6060 */
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int main(int argc, char *argv[])
{
    const char *port = argc > 1 ? argv[1] : "6060";
    struct addrinfo hints, *res, *ai;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_INET6;        /* a v6 socket also gets v4 on most systems */
    hints.ai_socktype = SOCK_DGRAM;
    hints.ai_flags = AI_PASSIVE;

    int rc = getaddrinfo(NULL, port, &hints, &res);
    if (rc != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc));
        return 1;
    }

    int fd = -1;
    for (ai = res; ai != NULL; ai = ai->ai_next) {
        fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
        if (fd == -1)
            continue;
        int off = 0;                   /* accept IPv4-mapped addresses too */
        setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof off);
        if (bind(fd, ai->ai_addr, ai->ai_addrlen) == 0)
            break;
        close(fd);
        fd = -1;
    }
    freeaddrinfo(res);
    if (fd == -1) {
        fprintf(stderr, "could not bind UDP port %s\n", port);
        return 1;
    }

    printf("waiting for readings on UDP port %s\n", port);
    for (;;) {
        char buf[512];
        struct sockaddr_storage from;
        socklen_t from_len = sizeof from;
        ssize_t n = recvfrom(fd, buf, sizeof buf - 1, 0,
                             (struct sockaddr *)&from, &from_len);
        if (n == -1) {
            perror("recvfrom");
            continue;
        }
        buf[n] = '\0';

        char host[NI_MAXHOST];
        getnameinfo((struct sockaddr *)&from, from_len, host, sizeof host,
                    NULL, 0, NI_NUMERICHOST);
        printf("%s sent %zd bytes: %s\n", host, n, buf);
    }
}

Points to notice:

  • SOCK_DGRAM and no listen()/accept(). A UDP socket is ready to receive the moment it’s bound.
  • Dual-stack. We ask for an AF_INET6 socket and clear IPV6_V6ONLY, so IPv4 senders also reach it. They appear as IPv4-mapped addresses like ::ffff:127.0.0.1. (Some systems default IPV6_V6ONLY to 1, which is why we set it explicitly.)
  • recvfrom() fills from with the sender’s address on every call; one socket hears from any number of senders.
  • We read at most sizeof buf - 1 bytes so there’s room for the '\0'.

The sender

/* sensor_send.c - send one UDP reading. Usage: ./sensor_send localhost 6060 "kitchen 21.5" */
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

int main(int argc, char *argv[])
{
    if (argc != 4) {
        fprintf(stderr, "usage: %s host port reading\n", argv[0]);
        return 1;
    }

    struct addrinfo hints, *res, *ai;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;
    hints.ai_socktype = SOCK_DGRAM;

    int rc = getaddrinfo(argv[1], argv[2], &hints, &res);
    if (rc != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rc));
        return 1;
    }

    int fd = -1;
    for (ai = res; ai != NULL; ai = ai->ai_next) {
        fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
        if (fd != -1)
            break;
    }
    if (fd == -1) {
        fprintf(stderr, "no usable address\n");
        freeaddrinfo(res);
        return 2;
    }

    ssize_t n = sendto(fd, argv[3], strlen(argv[3]), 0, ai->ai_addr, ai->ai_addrlen);
    if (n == -1)
        perror("sendto");
    else
        printf("sent %zd bytes to %s\n", n, argv[1]);

    freeaddrinfo(res);
    close(fd);
    return n == -1;
}

The sender doesn’t bind; the kernel assigns an ephemeral port on the first sendto(). It doesn’t connect either; the destination travels with each call.

Run it

gcc -Wall -o sensor_listen sensor_listen.c
gcc -Wall -o sensor_send sensor_send.c

./sensor_listen 6060
# another terminal
./sensor_send 127.0.0.1 6060 "garage 9.0"
./sensor_send ::1 6060 "attic 3"

Receiver output:

waiting for readings on UDP port 6060
::ffff:127.0.0.1 sent 10 bytes: garage 9.0
::1 sent 7 bytes: attic 3

Now stop the receiver and run the sender again. It still prints sent 10 bytes. UDP has no idea whether anyone received the datagram. “Sent” only means the kernel accepted it.

What UDP doesn’t do for you

ProblemWhat happensTypical remedy
LossDatagram silently disappearsAcknowledge and resend, or tolerate loss (send the next reading)
ReorderingReading 7 arrives before reading 6Put a sequence number in each datagram
DuplicationThe same datagram arrives twiceSequence numbers again; ignore repeats
No flow controlA fast sender overflows a slow receiver’s buffer; extras are droppedRate-limit, or enlarge SO_RCVBUF
SizeLarge datagrams fragment; one lost fragment loses allKeep payloads under ~1200 bytes

A minimal reliable request over UDP is “send, wait up to N ms for a reply, resend up to K times”. That’s how DNS clients behave. The waiting part uses a receive timeout from lesson 12.

Connected UDP sockets

If a client only ever talks to one server, connect() the UDP socket:

connect(fd, ai->ai_addr, ai->ai_addrlen);   /* no packets sent; just sets the peer */
send(fd, "kitchen 21.5", 12, 0);
char reply[64];
ssize_t n = recv(fd, reply, sizeof reply, 0);

Benefits: shorter calls, the kernel filters out datagrams from other addresses, and ICMP “port unreachable” errors are reported to you (as ECONNREFUSED on a later call) instead of being silently dropped.

When to choose UDP

  • Data that goes stale quickly: game state, live audio/video, sensor telemetry.
  • Small request-response exchanges where a retry is cheaper than a handshake: DNS, NTP.
  • Local discovery and announcements via broadcast or multicast.

If you’d end up reimplementing ordering, retransmission and flow control, use TCP (or a library such as QUIC that does it for you).

Key takeaways

  • UDP sockets need only bind() on the receiver; no listen, accept or connect.
  • recvfrom() reports the sender for each datagram; sendto() names the destination for each.
  • A successful sendto() says nothing about delivery.
  • Add sequence numbers, acknowledgements and timeouts yourself if you need reliability.

Exercises

  1. Add a sequence number to each reading ("17 kitchen 21.5") and make the receiver report gaps and out-of-order arrivals.
  2. Make the receiver reply ACK <seq> to each reading, and make the sender retry up to 3 times with a 500 ms receive timeout.
  3. Send 10,000 datagrams as fast as possible from one sender and count how many the receiver gets. Then raise SO_RCVBUF and compare.

Quiz

  1. Why does sensor_send report success even when no receiver is running?
  2. Why does an IPv4 sender show up as ::ffff:127.0.0.1?
  3. Name two benefits of calling connect() on a UDP socket.
Show answers
  1. sendto() only hands the datagram to the local kernel. UDP has no acknowledgements, so nothing reports whether it arrived.
  2. The receiver is an IPv6 socket with IPV6_V6ONLY off, so IPv4 peers are represented as IPv4-mapped IPv6 addresses.
  3. Any two of: you can use send/recv; the kernel only delivers datagrams from that peer; ICMP errors such as port unreachable are reported to you.

Finished this lesson?

Mark it complete to track your progress (saved in this browser).