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_DGRAMand nolisten()/accept(). A UDP socket is ready to receive the moment it’s bound.- Dual-stack. We ask for an
AF_INET6socket and clearIPV6_V6ONLY, so IPv4 senders also reach it. They appear as IPv4-mapped addresses like::ffff:127.0.0.1. (Some systems defaultIPV6_V6ONLYto 1, which is why we set it explicitly.) recvfrom()fillsfromwith the sender’s address on every call; one socket hears from any number of senders.- We read at most
sizeof buf - 1bytes 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
| Problem | What happens | Typical remedy |
|---|---|---|
| Loss | Datagram silently disappears | Acknowledge and resend, or tolerate loss (send the next reading) |
| Reordering | Reading 7 arrives before reading 6 | Put a sequence number in each datagram |
| Duplication | The same datagram arrives twice | Sequence numbers again; ignore repeats |
| No flow control | A fast sender overflows a slow receiver’s buffer; extras are dropped | Rate-limit, or enlarge SO_RCVBUF |
| Size | Large datagrams fragment; one lost fragment loses all | Keep 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
- Add a sequence number to each reading (
"17 kitchen 21.5") and make the receiver report gaps and out-of-order arrivals. - Make the receiver reply
ACK <seq>to each reading, and make the sender retry up to 3 times with a 500 ms receive timeout. - Send 10,000 datagrams as fast as possible from one sender and count how many the receiver gets. Then raise
SO_RCVBUFand compare.
Quiz
- Why does
sensor_sendreport success even when no receiver is running? - Why does an IPv4 sender show up as
::ffff:127.0.0.1? - Name two benefits of calling
connect()on a UDP socket.
Show answers
sendto()only hands the datagram to the local kernel. UDP has no acknowledgements, so nothing reports whether it arrived.- The receiver is an IPv6 socket with
IPV6_V6ONLYoff, so IPv4 peers are represented as IPv4-mapped IPv6 addresses. - 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.