UDP Sender and Receiver in C: sendto, recvfrom and Lost Datagrams

A UDP sender and receiver in C that runs on Linux and Windows, with sequence numbers to catch lost datagrams and tested demos of truncation and loss.

Separate envelopes travelling from one device to another, with one dashed red envelope lost on the way

Send 10,000 small UDP datagrams to a program on the same computer before it starts reading, and on a standard Linux setup only 256 of them arrive. The other 9,744 disappear, and neither sendto() nor recvfrom() reports an error. UDP behaves exactly as designed here: it delivers each datagram whole or not at all, and leaves noticing the losses to your program.

This guide builds a UDP sender and receiver in C that compile from the same source on Linux, macOS and Windows. It then measures the behaviors that catch people out: message boundaries, truncation, sending to a closed port, and loss. The receiver numbers each datagram so it can report the ones that never arrived, the way real telemetry and game protocols do. Every program was compiled and run for this article on Ubuntu 24.04 with GCC 13.3 and Clang 18 under -std=c11 and -std=c17 with -Wall -Wextra -pedantic and zero warnings, with clean AddressSanitizer and UndefinedBehaviorSanitizer runs, and cross-compiled for Windows with MinGW-w64. Output blocks come from real runs over the loopback interface. If you need reliable, ordered delivery instead, see the companion TCP client and server in C.

What Is UDP?

UDP (User Datagram Protocol) sends independent messages, called datagrams, from one program to another over IP. There is no connection and no handshake, and no retransmission: each datagram arrives whole or not at all, possibly out of order, and lost datagrams are not reported. A datagram’s boundaries are always preserved.

The protocol is defined in RFC 768, which is three pages long. That small size is the point: UDP adds only port numbers, a length and a checksum to IP, and leaves everything else to the application.

PropertyUDPTCP
ConnectionNone: just sendHandshake before any data
Unit of dataDatagram, boundaries preservedByte stream, no boundaries
DeliveryNot guaranteed, not reportedGuaranteed or the connection fails
OrderNot guaranteedGuaranteed
DuplicatesPossibleRemoved
Typical usesDNS, voice and video, games, telemetry, discovery, QUICWeb pages, file transfer, email, databases

UDP is the right choice when a late message is worth less than a fresh one. A game does not want a two-second-old position resent; it wants the next one. A temperature sensor sending a reading every second can lose one without anyone noticing. DNS fits too: one request, one reply, and the client simply asks again if nothing arrives.

How a UDP Sender and Receiver Work

A UDP sender and receiver, call by call SENDER RECEIVER getaddrinfo() socket() sendto() sendto() close() socket() bind(port) recvfrom() recvfrom() close() datagram 1 arrives whole × datagram 2 lost: no error anywhere No connection, no handshake: each sendto() is one datagram that arrives whole, or not at all. The receiver must be bound to its port first; the sender gets a temporary port automatically.
Figure 1: The calls a UDP sender and receiver make. Each sendto() sends one datagram, which arrives whole or not at all, and a lost datagram produces no error on either side.

The receiver creates a socket and binds it to a known port, then calls recvfrom() in a loop. The sender only needs a socket and the receiver’s address. It calls sendto(), and the operating system gives it a temporary port automatically. Each recvfrom() returns exactly one datagram, along with the sender’s address.

A Portable Sockets Layer for Linux and Windows

BSD sockets on Linux and macOS and Winsock 2 on Windows share almost the same API, but differ in the details. Windows needs WSAStartup() before any socket call, closes sockets with closesocket(), reports errors through WSAGetLastError() instead of errno, and takes timeouts in a DWORD rather than a struct timeval. (The Windows side is covered in more depth in Winsock programming.) A small header hides those differences, so the example programs read the same everywhere:

#ifndef UDP_H
#define UDP_H

/* A thin layer over BSD sockets (Linux, macOS) and Winsock 2 (Windows), so the
   example programs read the same on every platform. */

#ifndef _WIN32
#ifndef _POSIX_C_SOURCE
#define _POSIX_C_SOURCE 200809L    /* getaddrinfo, nanosleep, recvmsg */
#endif
#endif

#include <stdbool.h>
#include <stddef.h>

#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
typedef SOCKET socket_t;
#define BAD_SOCKET INVALID_SOCKET
#else
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
typedef int socket_t;
#define BAD_SOCKET (-1)
#endif

bool net_init(void);                 /* WSAStartup on Windows; nothing elsewhere */
void net_cleanup(void);
void close_socket(socket_t s);
int net_last_error(void);            /* errno, or WSAGetLastError() */
bool net_error_is_timeout(int err);
bool net_error_is_refused(int err);  /* the peer answered "port unreachable" */

/* Waits at most ms milliseconds in recvfrom() before failing with a timeout. */
bool set_recv_timeout(socket_t s, int ms);

/* A socket bound to port on every local address: IPv6 dual-stack when
   available, IPv4 otherwise. Returns BAD_SOCKET and fills err on failure. */
socket_t udp_bind(const char *port, char *err, size_t err_len);

/* Resolves host and port and opens a matching socket. The destination is
   stored in *dest for sendto(). */
socket_t udp_open(const char *host, const char *port, struct sockaddr_storage *dest,
                  socklen_t *dest_len, char *err, size_t err_len);

/* "127.0.0.1:5150" or "[::1]:5150" */
void format_address(const struct sockaddr *sa, char *out, size_t out_len);

#endif
#include "udp.h"

#include <stdio.h>
#include <string.h>

#ifndef _WIN32
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <sys/time.h>
#include <unistd.h>
#endif

bool net_init(void)
{
#ifdef _WIN32
    WSADATA wsa;
    return WSAStartup(MAKEWORD(2, 2), &wsa) == 0;
#else
    return true;
#endif
}

void net_cleanup(void)
{
#ifdef _WIN32
    WSACleanup();
#endif
}

void close_socket(socket_t s)
{
#ifdef _WIN32
    closesocket(s);
#else
    close(s);
#endif
}

int net_last_error(void)
{
#ifdef _WIN32
    return WSAGetLastError();
#else
    return errno;
#endif
}

bool net_error_is_timeout(int err)
{
#ifdef _WIN32
    return err == WSAETIMEDOUT;
#else
    return err == EAGAIN || err == EWOULDBLOCK;
#endif
}

bool net_error_is_refused(int err)
{
#ifdef _WIN32
    return err == WSAECONNRESET || err == WSAECONNREFUSED;
#else
    return err == ECONNREFUSED;
#endif
}

bool set_recv_timeout(socket_t s, int ms)
{
#ifdef _WIN32
    DWORD t = (DWORD)ms;
    return setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char *)&t, (socklen_t)sizeof t) == 0;
#else
    struct timeval t = {.tv_sec = ms / 1000, .tv_usec = (ms % 1000) * 1000};
    return setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &t, sizeof t) == 0;
#endif
}

socket_t udp_bind(const char *port, char *err, size_t err_len)
{
    static const int families[] = {AF_INET6, AF_INET};
    for (size_t i = 0; i < sizeof families / sizeof families[0]; i++) {
        struct addrinfo hints, *res = NULL;
        memset(&hints, 0, sizeof hints);
        hints.ai_family = families[i];
        hints.ai_socktype = SOCK_DGRAM;
        hints.ai_flags = AI_PASSIVE;           /* the "any" address */
        if (getaddrinfo(NULL, port, &hints, &res) != 0)
            continue;

        socket_t s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
        if (s != BAD_SOCKET) {
            if (res->ai_family == AF_INET6) {
                int off = 0;                   /* accept IPv4 too (dual-stack) */
                setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&off, (socklen_t)sizeof off);
            }
            if (bind(s, res->ai_addr, (socklen_t)res->ai_addrlen) == 0) {
                freeaddrinfo(res);
                return s;
            }
            close_socket(s);
        }
        freeaddrinfo(res);
    }
    snprintf(err, err_len, "cannot bind UDP port %s (error %d)", port, net_last_error());
    return BAD_SOCKET;
}

socket_t udp_open(const char *host, const char *port, struct sockaddr_storage *dest,
                  socklen_t *dest_len, char *err, size_t err_len)
{
    struct addrinfo hints, *res = NULL;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;               /* IPv4 or IPv6, whatever host resolves to */
    hints.ai_socktype = SOCK_DGRAM;
    int rc = getaddrinfo(host, port, &hints, &res);
    if (rc != 0) {
        snprintf(err, err_len, "cannot resolve %s: %s", host, gai_strerror(rc));
        return BAD_SOCKET;
    }
    socket_t s = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
    if (s == BAD_SOCKET) {
        snprintf(err, err_len, "socket() failed (error %d)", net_last_error());
    } else {
        memcpy(dest, res->ai_addr, res->ai_addrlen);
        *dest_len = (socklen_t)res->ai_addrlen;
    }
    freeaddrinfo(res);
    return s;
}

void format_address(const struct sockaddr *sa, char *out, size_t out_len)
{
    char ip[INET6_ADDRSTRLEN] = "?";
    unsigned port = 0;
    if (sa->sa_family == AF_INET) {
        const struct sockaddr_in *v4 = (const struct sockaddr_in *)(const void *)sa;
        inet_ntop(AF_INET, &v4->sin_addr, ip, sizeof ip);
        port = ntohs(v4->sin_port);
        snprintf(out, out_len, "%s:%u", ip, port);
    } else if (sa->sa_family == AF_INET6) {
        const struct sockaddr_in6 *v6 = (const struct sockaddr_in6 *)(const void *)sa;
        inet_ntop(AF_INET6, &v6->sin6_addr, ip, sizeof ip);
        port = ntohs(v6->sin6_port);
        snprintf(out, out_len, "[%s]:%u", ip, port);
    } else {
        snprintf(out, out_len, "(unknown address family)");
    }
}

Two functions do the real work:

  • udp_bind asks getaddrinfo() for the “any” address with AI_PASSIVE. It first tries IPv6 with IPV6_V6ONLY switched off, so one socket accepts both IPv6 and IPv4 datagrams (dual-stack), and falls back to plain IPv4 on systems without IPv6.
  • udp_open resolves a host name or address with getaddrinfo() and AF_UNSPEC, so 127.0.0.1, ::1 and localhost all work without separate code for each address family.

The UDP Receiver

Real-life example: a monitoring station collecting sensor readings. Each datagram starts with a sequence number. When a number is skipped, the receiver reports how many datagrams are missing instead of silently carrying on:

/* Receives datagrams on PORT and reports any gap in their sequence numbers.
   Stops after COUNT datagrams, or when none arrives for TIMEOUT_MS.
   Usage: udp-receiver PORT [COUNT] [TIMEOUT_MS] */
#include "udp.h"

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    if (argc < 2) {
        fprintf(stderr, "usage: %s PORT [COUNT] [TIMEOUT_MS]\n", argv[0]);
        return 2;
    }
    long want = argc > 2 ? strtol(argv[2], NULL, 10) : 0;      /* 0: no limit */
    long timeout = argc > 3 ? strtol(argv[3], NULL, 10) : 5000;
    if (!net_init())
        return 1;

    char err[256];
    socket_t s = udp_bind(argv[1], err, sizeof err);
    if (s == BAD_SOCKET || !set_recv_timeout(s, (int)timeout)) {
        fprintf(stderr, "%s\n", s == BAD_SOCKET ? err : "cannot set the timeout");
        net_cleanup();
        return 1;
    }
    printf("listening on UDP port %s\n", argv[1]);
    fflush(stdout);

    long got = 0, expected = 1, lost = 0;
    while (want == 0 || got < want) {
        char buf[1500];                         /* larger than any datagram we expect */
        struct sockaddr_storage from;
        socklen_t from_len = sizeof from;
        int n = (int)recvfrom(s, buf, (int)(sizeof buf - 1), 0, (struct sockaddr *)&from, &from_len);
        if (n < 0) {
            int e = net_last_error();
            if (net_error_is_refused(e))
                continue;                       /* Windows: an old "port unreachable" */
            if (net_error_is_timeout(e))
                printf("no datagram for %ld ms, stopping\n", timeout);
            else
                fprintf(stderr, "recvfrom failed (error %d)\n", e);
            break;
        }
        buf[n] = '\0';                          /* the payload is text in this example */
        got++;

        char who[80];
        format_address((const struct sockaddr *)&from, who, sizeof who);
        long seq = strtol(buf, NULL, 10);
        if (seq > expected) {
            lost += seq - expected;
            printf("  (missing %ld datagram(s) before this one)\n", seq - expected);
        }
        if (seq >= expected)
            expected = seq + 1;
        printf("from %s, %d bytes: %s\n", who, n, buf);
        fflush(stdout);
    }
    printf("received %ld datagram(s), %ld missing\n", got, lost);
    close_socket(s);
    net_cleanup();
    return 0;
}

The details that matter:

  • One recvfrom(), one datagram. The 1,500-byte buffer is larger than any datagram this sender produces. A datagram bigger than the buffer would be cut short, as the boundaries section shows.
  • A timeout instead of waiting forever. SO_RCVTIMEO makes recvfrom() fail after the given time, so the program can stop when the sender goes quiet.
  • Gap detection. A sequence number higher than the expected one means datagrams were lost, or are arriving late. One lower than expected is a late or duplicate datagram, and it is printed but not counted as a gap.
  • A Windows quirk. On Windows, a “port unreachable” reply to an earlier sendto() can surface as a WSAECONNRESET error from a later recvfrom() on the same socket, even though UDP has no connection. The receiver ignores that error and keeps reading.

The UDP Sender

/* Sends COUNT numbered datagrams to HOST:PORT, one every DELAY milliseconds.
   Usage: udp-sender HOST PORT MESSAGE [COUNT] [DELAY_MS]
   Example: udp-sender 127.0.0.1 5150 "boiler temp=71.3C" 5 */
#include "udp.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#define sleep_ms(ms) Sleep((DWORD)(ms))
#else
#include <time.h>
static void sleep_ms(long ms)
{
    struct timespec t = {.tv_sec = ms / 1000, .tv_nsec = (ms % 1000) * 1000000L};
    nanosleep(&t, NULL);
}
#endif

int main(int argc, char **argv)
{
    if (argc < 4) {
        fprintf(stderr, "usage: %s HOST PORT MESSAGE [COUNT] [DELAY_MS]\n", argv[0]);
        return 2;
    }
    long count = argc > 4 ? strtol(argv[4], NULL, 10) : 1;
    long delay = argc > 5 ? strtol(argv[5], NULL, 10) : 100;
    if (count < 1 || delay < 0) {
        fprintf(stderr, "COUNT must be at least 1 and DELAY_MS not negative\n");
        return 2;
    }
    if (!net_init())
        return 1;

    char err[256];
    struct sockaddr_storage dest;
    socklen_t dest_len = 0;
    socket_t s = udp_open(argv[1], argv[2], &dest, &dest_len, err, sizeof err);
    if (s == BAD_SOCKET) {
        fprintf(stderr, "%s\n", err);
        net_cleanup();
        return 1;
    }

    char where[80];
    format_address((const struct sockaddr *)&dest, where, sizeof where);
    for (long seq = 1; seq <= count; seq++) {
        char datagram[1024];
        int n = snprintf(datagram, sizeof datagram, "%ld %s", seq, argv[3]);
        if (n < 0 || (size_t)n >= sizeof datagram) {
            fprintf(stderr, "message too long\n");
            break;
        }
        /* One sendto() is one datagram: it arrives whole or not at all. */
        if (sendto(s, datagram, n, 0, (const struct sockaddr *)&dest, dest_len) != n) {
            fprintf(stderr, "sendto failed (error %d)\n", net_last_error());
            break;
        }
        printf("sent %d bytes to %s: %s\n", n, where, datagram);
        fflush(stdout);
        if (seq < count)
            sleep_ms(delay);
    }
    close_socket(s);
    net_cleanup();
    return 0;
}

sendto() returns as soon as the datagram is handed to the operating system. A successful return means the datagram left this program, not that it arrived anywhere. The sender adds a sequence number to each message. That is the cheapest way to give the receiver something to check, and it is the same idea RTP uses for voice and video.

Running the Sender and Receiver

Start the receiver in one terminal and the sender in another:

./udp-receiver 5150
./udp-sender 127.0.0.1 5150 "boiler temp=71.3C" 2

The repository’s test does this automatically. It runs two IPv4 sends, one IPv6 send when the machine has an IPv6 loopback, and then a hand-made datagram with sequence number 5. Here is one run:

Output:

--- sender (IPv4)
sent 19 bytes to 127.0.0.1:42987: 1 boiler temp=71.3C
sent 19 bytes to 127.0.0.1:42987: 2 boiler temp=71.3C
--- sender (IPv6)
socket() failed (error 97)
(no IPv6 loopback)
--- receiver
listening on UDP port 42987
from 127.0.0.1:56543, 19 bytes: 1 boiler temp=71.3C
from 127.0.0.1:56543, 19 bytes: 2 boiler temp=71.3C
  (missing 2 datagram(s) before this one)
from 127.0.0.1:47449, 14 bytes: 5 jumped ahead
no datagram for 3000 ms, stopping
received 3 datagram(s), 2 missing

The receiver’s last datagram carried number 5 when it expected 3, so it reported 2 missing. Nothing on the network failed. The receiver simply knows what it should have seen, which is the only way a UDP program can detect loss. On a dual-stack socket an IPv4 sender appears as an IPv4-mapped address such as ::ffff:127.0.0.1. This machine had no IPv6, so the receiver fell back to an IPv4 socket and shows plain 127.0.0.1.

Datagrams Keep Their Boundaries

This program sends four datagrams over the loopback interface, of 5, 1, 300 and 0 bytes, then receives them. It then sends a 300-byte datagram to a 4-byte buffer:

/* What a datagram socket preserves: message boundaries, empty messages, and
   what happens when the receive buffer is too small. Loopback only. */
#include "udp.h"

#include <stdio.h>
#include <string.h>
#ifndef _WIN32
#include <arpa/inet.h>
#include <netinet/in.h>
#endif

/* A socket bound to 127.0.0.1 on a port the system picks; *addr gets that port. */
static socket_t loopback_socket(struct sockaddr_in *addr)
{
    socket_t s = socket(AF_INET, SOCK_DGRAM, 0);
    memset(addr, 0, sizeof *addr);
    addr->sin_family = AF_INET;
    addr->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    socklen_t len = sizeof *addr;
    if (s == BAD_SOCKET || bind(s, (struct sockaddr *)addr, len) != 0 ||
        getsockname(s, (struct sockaddr *)addr, &len) != 0)
        return BAD_SOCKET;
    set_recv_timeout(s, 1000);
    return s;
}

/* Returns the bytes kept, and sets *truncated if the datagram did not fit. */
static int receive(socket_t s, char *buf, int cap, bool *truncated)
{
#ifdef _WIN32
    int n = recv(s, buf, cap, 0);
    *truncated = n < 0 && WSAGetLastError() == WSAEMSGSIZE;
    return *truncated ? cap : n;
#else
    struct iovec iov = {.iov_base = buf, .iov_len = (size_t)cap};
    struct msghdr msg;
    memset(&msg, 0, sizeof msg);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
    int n = (int)recvmsg(s, &msg, 0);
    *truncated = n >= 0 && (msg.msg_flags & MSG_TRUNC);
    return n;
#endif
}

int main(void)
{
    if (!net_init())
        return 1;
    struct sockaddr_in to;
    socket_t rx = loopback_socket(&to);
    socket_t tx = socket(AF_INET, SOCK_DGRAM, 0);
    if (rx == BAD_SOCKET || tx == BAD_SOCKET) {
        fprintf(stderr, "cannot open loopback sockets\n");
        return 1;
    }

    char big[300];
    memset(big, 'x', sizeof big);
    const struct { const char *data; int len; } sends[] = {
        {"hello", 5}, {"!", 1}, {big, 300}, {"", 0},
    };
    for (size_t i = 0; i < sizeof sends / sizeof sends[0]; i++)
        sendto(tx, sends[i].data, sends[i].len, 0, (struct sockaddr *)&to, (socklen_t)sizeof to);

    printf("sent datagrams of 5, 1, 300 and 0 bytes\n");
    for (size_t i = 0; i < sizeof sends / sizeof sends[0]; i++) {
        char buf[2048];
        bool cut;
        int n = receive(rx, buf, (int)sizeof buf, &cut);
        printf("receive %zu returned %d bytes\n", i + 1, n);
    }

    /* The same 300-byte datagram into a 4-byte buffer. */
    sendto(tx, big, 300, 0, (struct sockaddr *)&to, (socklen_t)sizeof to);
    sendto(tx, "next", 4, 0, (struct sockaddr *)&to, (socklen_t)sizeof to);
    char tiny[4];             /* not "small": windows.h defines small as a macro */
    bool cut = false;
    int n = receive(rx, tiny, (int)sizeof tiny, &cut);
    printf("300 bytes into a 4-byte buffer: kept %d, truncated: %s\n", n, cut ? "yes" : "no");
    char buf[2048];
    n = receive(rx, buf, (int)sizeof buf, &cut);
    printf("the next receive returned the next datagram: %d bytes, \"%.*s\"\n", n, n, buf);

    close_socket(tx);
    close_socket(rx);
    net_cleanup();
    return 0;
}

Output:

sent datagrams of 5, 1, 300 and 0 bytes
receive 1 returned 5 bytes
receive 2 returned 1 bytes
receive 3 returned 300 bytes
receive 4 returned 0 bytes
300 bytes into a 4-byte buffer: kept 4, truncated: yes
the next receive returned the next datagram: 4 bytes, "next"
The same three sends over UDP and over TCP SENT: 5 BYTES, 1 BYTE, 300 BYTES hello ! 300 x UDP: THREE RECEIVES, THREE DATAGRAMS (measured) 5 1 300 TCP: ONE BYTE STREAM, READ IN ANY SIZES (illustrative) recv 1: 306 bytes? 120? recv 2: whatever is left UDP keeps each message separate, so no length prefix or delimiter is needed. TCP merges and splits data freely; the reader must find message boundaries itself.
Figure 2: UDP preserves message boundaries; TCP does not. The UDP sizes are from the boundaries program’s output; the TCP row is illustrative, since TCP chooses its own read sizes.

Three results here are different from TCP:

  • Each receive returned exactly one datagram. The 5-byte and 1-byte messages were not merged, so a UDP protocol needs no length prefix or delimiter between messages.
  • A zero-length datagram is a real message. The fourth receive returned 0 bytes. In TCP, 0 from recv() means the connection closed. In UDP it is just an empty datagram, so do not treat 0 as end-of-file.
  • A short buffer truncates, and the rest is gone. The 300-byte datagram into a 4-byte buffer kept 4 bytes, and the next receive returned the next datagram, not the remaining 296 bytes. POSIX reports this through the MSG_TRUNC flag from recvmsg(); Windows reports it as a WSAEMSGSIZE error. Size your buffer for the largest datagram you accept. The largest UDP payload over IPv4 is 65,507 bytes.

Connected UDP and “Port Unreachable”

UDP sockets can call connect(). It sends nothing, but it fixes the peer address, lets you use send() and recv(), filters out datagrams from anyone else, and brings back one thing unconnected sockets lose:

/* Sending to a port where nobody is listening: unconnected vs connected UDP. */
#include "udp.h"

#include <stdio.h>
#include <string.h>
#ifndef _WIN32
#include <arpa/inet.h>
#include <netinet/in.h>
#endif

int main(void)
{
    if (!net_init())
        return 1;

    /* Find a free loopback port, then close it so nothing listens there. */
    struct sockaddr_in closed;
    memset(&closed, 0, sizeof closed);
    closed.sin_family = AF_INET;
    closed.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    socklen_t len = sizeof closed;
    socket_t probe = socket(AF_INET, SOCK_DGRAM, 0);
    if (probe == BAD_SOCKET || bind(probe, (struct sockaddr *)&closed, len) != 0 ||
        getsockname(probe, (struct sockaddr *)&closed, &len) != 0)
        return 1;
    close_socket(probe);

    /* Unconnected: sendto() succeeds and nothing ever reports the failure. */
    socket_t a = socket(AF_INET, SOCK_DGRAM, 0);
    int n = (int)sendto(a, "hello", 5, 0, (struct sockaddr *)&closed, (socklen_t)sizeof closed);
    printf("unconnected sendto to a closed port returned %d\n", n);
    close_socket(a);

    /* Connected: the kernel remembers the peer and reports its ICMP error. */
    socket_t b = socket(AF_INET, SOCK_DGRAM, 0);
    if (connect(b, (struct sockaddr *)&closed, (socklen_t)sizeof closed) != 0)
        return 1;
    set_recv_timeout(b, 1000);
    n = (int)send(b, "hello", 5, 0);
    printf("connected send to the same port returned %d\n", n);
    char buf[16];
    n = (int)recv(b, buf, (int)sizeof buf, 0);
    int e = net_last_error();
    if (n < 0 && net_error_is_refused(e))
        printf("the next recv failed: port unreachable (nobody is listening)\n");
    else if (n < 0 && net_error_is_timeout(e))
        printf("the next recv timed out: no error was reported\n");
    else
        printf("the next recv returned %d (error %d)\n", n, e);
    close_socket(b);
    net_cleanup();
    return 0;
}

Output:

unconnected sendto to a closed port returned 5
connected send to the same port returned 5
the next recv failed: port unreachable (nobody is listening)

Both sends to the closed port “succeeded”. The receiving machine answered with an ICMP “port unreachable” message (ICMP is the same protocol behind ping in C), and only the connected socket saw it: the next recv() failed with ECONNREFUSED on Linux (WSAECONNRESET on Windows). An unconnected socket sending to the same port gets no sign of the failure at all. When a program talks to one peer, connecting the socket is the cheapest way to learn that nobody is listening.

How Often Are UDP Datagrams Lost? An Experiment

Loss is usually blamed on the network, but the most common place a datagram dies is the receiver’s own socket buffer. When it is full, the kernel drops new datagrams without telling anyone. This program sends datagrams to a socket that is not reading yet, then counts how many survived:

/* Sends COUNT datagrams to a socket that is not reading yet, then counts how
   many survived. Usage: loss_test [COUNT] [RCVBUF_BYTES]   (0 = system default) */
#include "udp.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef _WIN32
#include <arpa/inet.h>
#include <netinet/in.h>
#endif

int main(int argc, char **argv)
{
    long count = argc > 1 ? strtol(argv[1], NULL, 10) : 10000;
    int rcvbuf = argc > 2 ? (int)strtol(argv[2], NULL, 10) : 0;
    if (count < 1 || !net_init())
        return 2;

    struct sockaddr_in to;
    memset(&to, 0, sizeof to);
    to.sin_family = AF_INET;
    to.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    socklen_t len = sizeof to;
    socket_t rx = socket(AF_INET, SOCK_DGRAM, 0);
    socket_t tx = socket(AF_INET, SOCK_DGRAM, 0);
    if (rx == BAD_SOCKET || tx == BAD_SOCKET)
        return 1;
    if (rcvbuf > 0)
        setsockopt(rx, SOL_SOCKET, SO_RCVBUF, (const char *)&rcvbuf, (socklen_t)sizeof rcvbuf);
    if (bind(rx, (struct sockaddr *)&to, len) != 0 || getsockname(rx, (struct sockaddr *)&to, &len) != 0)
        return 1;
    int actual = 0;
    socklen_t optlen = sizeof actual;
    getsockopt(rx, SOL_SOCKET, SO_RCVBUF, (char *)&actual, &optlen);

    /* Blast every datagram before the receiver reads anything. */
    long send_errors = 0;
    for (long seq = 1; seq <= count; seq++) {
        char msg[64];
        int n = snprintf(msg, sizeof msg, "%ld reading", seq);
        if (sendto(tx, msg, n, 0, (struct sockaddr *)&to, (socklen_t)sizeof to) != n)
            send_errors++;
    }

    set_recv_timeout(rx, 200);
    long got = 0, last = 0, out_of_order = 0;
    char buf[128];
    int n;
    while ((n = (int)recv(rx, buf, (int)(sizeof buf - 1), 0)) > 0) {
        buf[n] = '\0';
        long seq = strtol(buf, NULL, 10);
        if (seq < 1 || seq > count || strstr(buf, " reading") == NULL)
            return 1;                                 /* corrupted: never expected */
        if (seq <= last)
            out_of_order++;
        last = seq;
        got++;
    }

    printf("receive buffer: requested %s, actual %d bytes\n", rcvbuf > 0 ? argv[2] : "default", actual);
    printf("sent %ld, send errors %ld, received %ld, lost %ld (%.1f%%), out of order %ld\n",
           count, send_errors, got, count - got, 100.0 * (double)(count - got) / (double)count,
           out_of_order);
    close_socket(tx);
    close_socket(rx);
    net_cleanup();
    return got > 0 && got <= count && out_of_order == 0 ? 0 : 1;
}

Output, three receive-buffer sizes, 10,000 datagrams of 9 to 13 bytes:

loss_test 10000 4096

receive buffer: requested 4096, actual 8192 bytes
sent 10000, send errors 0, received 9, lost 9991 (99.9%), out of order 0

loss_test 10000 0

receive buffer: requested default, actual 212992 bytes
sent 10000, send errors 0, received 256, lost 9744 (97.4%), out of order 0

loss_test 10000 1048576

receive buffer: requested 1048576, actual 2097152 bytes
sent 10000, send errors 0, received 2520, lost 7480 (74.8%), out of order 0

The results were identical on every repeat run on this machine:

  • The default buffer held 256 datagrams of about 10 bytes each, out of 10,000. Linux reported a 212,992-byte buffer, which works out to roughly 832 bytes of buffer per datagram. That is an inference: each datagram is charged for the kernel’s bookkeeping, not just its payload, so small datagrams fill a buffer far faster than their size suggests.
  • Asking for 4,096 bytes got 8,192. Linux doubles the value passed to SO_RCVBUF to allow for that overhead (see udp(7) and socket(7)). Only 9 datagrams fitted.
  • A 1 MiB request was granted 2 MiB here and kept 2,520. On a stock Ubuntu system the kernel caps the request at net.core.rmem_max, so expect less unless that limit is raised.
  • Windows keeps far more, but not all. The same 4,096-byte request on Windows 11 kept 383 of 10,000, against 9 on Linux (see the table at the end). Windows does not charge small datagrams against the buffer the same way, but it still dropped 96%.
  • Nothing arrived out of order or corrupted in any run. On loopback, the only failure was dropping.

The experiment is deliberately harsh, because the receiver reads nothing until the sender has finished. A real receiver reads continuously, but the lesson holds. If datagrams arrive faster than your program reads them, the excess is dropped silently. The fixes are reading in a dedicated thread, a larger receive buffer, and sequence numbers so you can tell when it happened. Cloudflare’s guide to UDP sockets covers the server-side tuning in depth.

Common Mistakes with UDP in C

  • Assuming sendto() means delivered. It means handed to the operating system. Only a reply from the receiver proves arrival.
  • Treating UDP like a stream. Calling recv() in a loop to “read the rest” of a message reads the next datagram instead. Read each message in one call with a buffer large enough for it.
  • Treating a 0-byte receive as end-of-file. It is an empty datagram. UDP has no end-of-file.
  • Forgetting the receive buffer. A slow reader loses datagrams at the socket, not on the network. Measure with sequence numbers before blaming the network.
  • Sending datagrams near the size limit. A datagram larger than the path’s MTU (often 1,500 bytes on Ethernet) is split into IP fragments, and losing any fragment loses the whole datagram. Keep datagrams under about 1,200 bytes unless you control the network.
  • Forgetting htons() when filling in a port by hand. Ports in socket addresses are in network byte order. getaddrinfo(), used throughout this code, does the conversion for you.
  • Ignoring the Windows WSAECONNRESET on unconnected sockets. A late “port unreachable” can make a server’s recvfrom() fail. Skip that error and keep reading, as the receiver does.

Key Takeaways

  • UDP sends independent datagrams. Each arrives whole or not at all, with no connection, no retransmission and no loss report.
  • Message boundaries are preserved. One sendto() is one recvfrom(), a 0-byte datagram is a real message, and a too-small buffer truncates and discards the rest.
  • A successful sendto() proves nothing about delivery. Even a send to a closed port succeeded. Only a connected socket heard the “port unreachable” reply.
  • The receive buffer is the first place datagrams die. With nobody reading, a default Linux buffer kept 256 of 10,000 small datagrams, about 832 bytes of buffer each.
  • Number your datagrams. Sequence numbers are the cheapest way to detect loss, reordering and duplicates.
  • One source can serve Linux and Windows with a thin layer over WSAStartup, closesocket, error codes and timeouts.

Conclusion

UDP gives you less than TCP and asks you to decide what to do about the rest. That makes it the right tool when timeliness matters more than completeness, and the wrong one when every byte must arrive. The sender and receiver here are short. The interesting code is the part that notices what went missing, because UDP itself never will.

The next steps are acknowledgements and retries for messages that must arrive, or the reverse: a fixed-rate stream where the receiver interpolates over gaps. For the reliable side of networking, and the rest of the language, see the C programming section.

Source Code and Tests

udp workflow status

All programs on this page are in the networking/udp directory of the MYCPLUS C examples repository.

Build and test:

cmake -S . -B build
cmake --build build
ctest --test-dir build --output-on-failure

What the build checks.

  • Compilers: GCC and Clang under C11 and C17 with -Wall -Wextra -pedantic -Werror, and MSVC under /W4 /WX.
  • Output: boundaries and connected print exactly the output shown here.
  • Loss test: loss_test runs with a small and a default buffer and checks what holds on every system. Something arrives, nothing is corrupted or duplicated, and nothing arrives out of order. The number lost is not checked, because it depends on the system.
  • Linux and macOS: the receiver gets datagrams from IPv4 and IPv6 senders and reports a gap.
  • Sanitizers: the programs and the sender/receiver test run clean under AddressSanitizer and UndefinedBehaviorSanitizer.

The build does not test a real network, where loss, reordering and duplication come from routers and links.

What I Verified

Everything in the Ubuntu column was run for this article on Ubuntu 24.04 (x86-64, GCC 13.3, Clang 18, CMake 3.28, MinGW-w64 GCC 13). The WSL and Windows columns come from the run_all.sh and run_all.ps1 scripts in the repository.

CheckUbuntu 24.04WSL (Ubuntu 24.04)Windows 11
Builds with warnings as errors (GCC and Clang on Linux, MSVC /W4 /WX on Windows), C11 and C17GCC and Clang, C11 and C17: passed, zero warningsGCC 13.3 and Clang, C11 and C17: passed, zero warningsMSVC /W4 /WX, C11 and C17: built
Tests (boundaries and connected output, loss invariants, usage error; on Linux also the sender/receiver test)6 of 6 passed in all four configurations6 of 6 passed in all four configurations5 of 5 passed in C11 and C17 (the sender/receiver test is Linux and macOS only)
AddressSanitizer and UndefinedBehaviorSanitizer over all programs and the sender/receiver testCleanCleanNot applicable
Windows build cross-compiled with MinGW-w64, warnings as errorsPassedNot runNot applicable
10,000 datagrams into a 4,096-byte receive buffersent 10000, send errors 0, received 9, lost 9991 (99.9%), out of order 0sent 10000, send errors 0, received 11, lost 9989 (99.9%), out of order 0sent 10000, send errors 0, received 383, lost 9617 (96.2%), out of order 0
8 deliberate mistakes injected to check the tests6 caught; the 2 that survived change nothing these tests can observe (the pause between sends, and an order check that never triggers on loopback)Not runNot run

Not covered: a real network between two machines, IPv6 on the Ubuntu test machine (it has no IPv6 loopback, so the IPv6 send is checked only on machines that have one), macOS, and any timing.

Scroll to Top