A PXE client reads two files by TFTP (octet mode, 512-byte blocks, no losses): pxelinux.0 of 1,300 bytes and menu.cfg of 1,024 bytes. For each, list the DATA blocks and count every packet, including the RRQ.
UDP sockets exchange independent datagrams with sendto() and recvfrom() — no connection, no delivery guarantee, but message boundaries kept. This article covers the C and Java APIs, connected UDP, and two classic UDP protocols: TFTP's lock-step file transfer and DNS queries.
socket(AF_INET, SOCK_DGRAM, 0). Server: socket → bind → loop of recvfrom/sendto. Client: socket → sendto → recvfrom → close. No listen(), accept() or handshake.sendto() names the destination in every call; recvfrom() returns one whole datagram plus the sender's address. Boundaries are preserved, and a 0-byte datagram is legal — not end-of-file.recvfrom() blocked forever, so clients need timeouts (SO_RCVTIMEO, select()) and retransmission.connect() on a UDP socket sends nothing: it records the peer, allows send()/recv(), filters other senders and lets ICMP errors such as ECONNREFUSED reach the program.DatagramSocket sends and receives DatagramPacket objects (data, length, address, port); setSoTimeout() bounds receive(); MulticastSocket joins multicast groups.A datagram socket (SOCK_DGRAM) sends and receives individual UDP messages. There is no connection and no stream: each send call puts exactly one datagram on the network, carrying its own destination address, and each receive call returns exactly one datagram together with the address of whoever sent it. UDP itself (RFC 768) adds only port numbers and a checksum to IP, so the socket inherits IP's best-effort service.
SOCK_STREAM)SOCK_DGRAM)<sys/socket.h>ssize_t sendto(int sockfd, const void *buf, size_t nbytes, int flags,
const struct sockaddr *to, socklen_t addrlen);
/* returns the number of bytes sent, or -1 */
ssize_t recvfrom(int sockfd, void *buf, size_t nbytes, int flags,
struct sockaddr *from, socklen_t *addrlen);
/* returns the datagram's size (0 is legal), or -1;
from and addrlen may be NULL if the sender does not matter */The first four arguments are those of send() and recv(). sendto() adds the destination socket address; recvfrom() adds a buffer for the sender's address and a value-result length — set *addrlen to the buffer's size before the call and read the actual size after it. A datagram of 0 bytes is perfectly legal (an 8-byte UDP header with no data), so a return value of 0 is not end-of-file the way it is for TCP.
MSG_TRUNC flag), so size buffers for the largest message the protocol allows.SO_RCVBUF only delays the problem.Because nothing is guaranteed, a client waiting in recvfrom() for a reply that was lost — or for a server that is not running — blocks forever. Every real UDP client therefore sets a timeout and retries: with setsockopt(SO_RCVTIMEO) (recvfrom then fails with EAGAIN/EWOULDBLOCK), with select() or poll() and a timeout, or with an alarm() signal. Retries should back off, waiting longer each time, as DNS resolvers and TFTP implementations do.
The UDP echo server needs neither listen() nor accept(), and it is iterative: one socket and one loop serve every client, because each request is a single datagram that can be answered at once. Stevens sums it up: most TCP servers are concurrent, most UDP servers are iterative. It can even share port number 9877 with the TCP echo server — TCP and UDP ports are separate number spaces.
/* udp_echo_server.c — iterative UDP echo server: one socket serves every client */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERV_PORT 9877
int main(void) {
int sockfd;
struct sockaddr_in servaddr, cliaddr;
socklen_t len;
ssize_t n;
static char msg[65535]; /* room for the largest datagram */
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); exit(1); }
memset(&servaddr, 0, sizeof servaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
if (bind(sockfd, (struct sockaddr *) &servaddr, sizeof servaddr) < 0) { perror("bind"); exit(1); }
for (;;) { /* no listen(), no accept() */
len = sizeof cliaddr; /* value-result: reset before every call */
n = recvfrom(sockfd, msg, sizeof msg, 0, (struct sockaddr *) &cliaddr, &len);
if (n < 0) { perror("recvfrom"); continue; }
sendto(sockfd, msg, (size_t) n, 0, (struct sockaddr *) &cliaddr, len); /* back to the sender */
}
}/* udp_echo_client.c — send each line as one datagram; give up on a reply after 2 s */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define SERV_PORT 9877
int main(int argc, char *argv[]) {
int sockfd;
struct sockaddr_in servaddr, from;
socklen_t len;
struct timeval tv = { 2, 0 }; /* 2-second receive timeout */
char line[4096], reply[4097];
ssize_t n;
if (argc != 2) { fprintf(stderr, "usage: %s server-IPv4-address\n", argv[0]); exit(1); }
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("socket"); exit(1); }
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
memset(&servaddr, 0, sizeof servaddr);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) != 1) { fputs("bad address\n", stderr); exit(1); }
while (fgets(line, sizeof line, stdin) != NULL) {
sendto(sockfd, line, strlen(line), 0, (struct sockaddr *) &servaddr, sizeof servaddr);
do {
len = sizeof from;
n = recvfrom(sockfd, reply, sizeof reply - 1, 0, (struct sockaddr *) &from, &len);
} while (n >= 0 && (from.sin_addr.s_addr != servaddr.sin_addr.s_addr ||
from.sin_port != servaddr.sin_port)); /* ignore strangers */
if (n < 0) { fputs("no reply: datagram lost or server down\n", stderr); continue; }
reply[n] = '\0';
fputs(reply, stdout);
}
close(sockfd); /* sends nothing: there is no connection */
return 0;
}Start the server, run the client and type a few lines. Then stop the server and type again: the client cannot tell that the server is gone, because the ICMP port unreachable message that comes back is not delivered to an unconnected UDP socket — only the 2-second timeout rescues it. Compare TCP, where connect() would fail at once with Connection refused.
nc -u 127.0.0.1 9877 is a ready-made UDP client for testing. Notice that the server keeps no per-client state at all — which is why a single DNS server can answer an enormous number of clients.A UDP socket may call connect(). Nothing is sent — there is no handshake. The kernel checks for immediate errors (such as an unreachable network), records the peer's IP address and port, and returns. The result is a connected UDP socket: still unreliable and still message-oriented, but tied to that one peer.
| Aspect | Unconnected UDP socket | Connected UDP socket |
|---|---|---|
| Sending | sendto() with a destination every time | send() or write(); BSD kernels reject a destination in sendto() with EISCONN |
| Receiving | recvfrom() returns datagrams from any sender | recv() or read(); only datagrams from the connected peer are delivered |
| Asynchronous ICMP errors (port unreachable) | Not reported — the program just waits | Returned on a later call, e.g. recv() fails with ECONNREFUSED |
| Kernel work per datagram | BSD-derived kernels connect, send and disconnect internally for each sendto() | The peer is set once, so sending many datagrams is faster |
| Changing the peer | Free on every call | Call connect() again; connect() with family AF_UNSPEC disconnects |
| Typical user | Servers that talk to many clients | Clients that talk to one server, such as a stub resolver configured with a single DNS server |
<errno.h>)connect(sockfd, (struct sockaddr *) &servaddr, sizeof servaddr); /* sends nothing */
send(sockfd, line, strlen(line), 0); /* goes to the connected peer */
n = recv(sockfd, reply, sizeof reply - 1, 0); /* only that peer's datagrams arrive */
if (n < 0 && errno == ECONNREFUSED) /* ICMP port unreachable came back */
fputs("server not running\n", stderr);Java models UDP with two classes. A DatagramSocket is the endpoint: new DatagramSocket(9877) creates and binds a server socket, while new DatagramSocket() gives a client an ephemeral port. A DatagramPacket is one message — a byte array and a length, plus the destination InetAddress and port when sending. send(packet) is Java's sendto(); receive(packet) is recvfrom(): it blocks, then fills the packet with the data, the real length, and the sender's address and port.
import java.net.*;
public class UdpEchoServer {
public static void main(String[] args) throws Exception {
try (DatagramSocket socket = new DatagramSocket(9877)) { // socket + bind
byte[] buf = new byte[65535];
while (true) {
DatagramPacket request = new DatagramPacket(buf, buf.length);
socket.receive(request); // blocks, like recvfrom()
DatagramPacket reply = new DatagramPacket(
request.getData(), request.getLength(), // the same bytes ...
request.getAddress(), request.getPort()); // ... back to the sender
socket.send(reply); // like sendto()
}
}
}
}import java.net.*;
import java.nio.charset.StandardCharsets;
public class UdpEchoClient {
public static void main(String[] args) throws Exception {
InetAddress server = InetAddress.getByName(args.length > 0 ? args[0] : "127.0.0.1");
byte[] out = "hello, UDP".getBytes(StandardCharsets.UTF_8);
try (DatagramSocket socket = new DatagramSocket()) { // any free (ephemeral) port
socket.setSoTimeout(2000); // receive() waits at most 2 s
socket.send(new DatagramPacket(out, out.length, server, 9877));
DatagramPacket reply = new DatagramPacket(new byte[65535], 65535);
try {
socket.receive(reply);
System.out.println(new String(reply.getData(), 0, reply.getLength(),
StandardCharsets.UTF_8));
} catch (SocketTimeoutException e) {
System.out.println("no reply: the datagram or its echo was lost");
}
}
}
}setSoTimeout(ms) makes receive() throw SocketTimeoutException instead of waiting forever — Java's SO_RCVTIMEO.connect(address, port) turns a DatagramSocket into a connected UDP socket, exactly as in C; disconnect() undoes it.MulticastSocket, a subclass, can joinGroup() a multicast address such as 239.1.2.3 — something TCP cannot do.packet.getLength(), not buf.length, when turning received bytes into a string: the buffer is usually larger than the message, and the bytes after getLength() are zeros or leftovers from an earlier datagram.TFTP, the Trivial File Transfer Protocol, is FTP stripped to the bone so that it fits in a network card's boot ROM. It can only read or write a whole file — there is no log-in, no directory listing, no rename or delete. It runs over UDP, and the client sends its first request to port 69. First specified in RFC 783 (1981), its current definition is RFC 1350 (1992); RFCs 2347–2349 later added negotiable options.
| Opcode | Packet | Format |
|---|---|---|
| 1 | RRQ — read request | opcode · file name · 0 · mode · 0 |
| 2 | WRQ — write request | opcode · file name · 0 · mode · 0 |
| 3 | DATA | opcode · block number · 0–512 bytes of data |
| 4 | ACK | opcode · block number |
| 5 | ERROR | opcode · error code · message · 0 |
RRQ for boot.img in octet mode — 17 bytes, sent to port 69:
00 01 opcode 1 = RRQ
62 6f 6f 74 2e 69 6d 67 "boot.img"
00 end of the file name
6f 63 74 65 74 "octet"
00 end of the mode
DATA block 1 — 2 + 2 + 512 = 516 bytes: 00 03 00 01 then 512 data bytes
ACK block 1 — 4 bytes: 00 04 00 01
ERROR 1 — "File not found": 00 05 00 01 46 69 6c 65 20 6e 6f 74 20 66 6f 75 6e 64 00Modes and errors. netascii carries text using the TELNET NVT rules (8-bit ASCII, lines ending CR LF), so each side converts to its local line endings; octet carries raw bytes and is used for binaries such as boot images and firmware; a third mode, mail, is obsolete. Error codes: 0 not defined (see the message), 1 file not found, 2 access violation, 3 disk full, 4 illegal TFTP operation, 5 unknown transfer ID, 6 file already exists, 7 no such user.
Where it is used. PCs and diskless workstations booting over the network with PXE get an IP address and a boot-file name from DHCP (or BOOTP), then download that file by TFTP; routers, switches and VoIP phones fetch firmware and configuration the same way. With no authentication, TFTP servers are confined to one directory (often /tftpboot) on trusted networks. Two classic limits: stop-and-wait moves at most one 512-byte block per round trip, and 16-bit block numbers capped files near 32 MB — the blksize option (RFC 2348) allows larger blocks.
DNS is the busiest UDP application on the Internet. The stub resolver inside a client (the library behind getaddrinfo()) sends one query datagram to a recursive resolver on UDP port 53, and one reply datagram comes back. A lost packet costs only a retry, whereas TCP would spend a full round trip on the handshake before the question could even be asked. Name space, record types and resolution steps are covered in the DNS & e-mail protocols topic; here the focus is the exchange at the socket level.
| Field | Bits | Purpose |
|---|---|---|
| ID | 16 | Chosen by the client and copied into the reply, so the client can match reply to query |
| QR | 1 | 0 = query, 1 = response |
| Opcode | 4 | 0 = standard query |
| AA | 1 | Authoritative answer — set by a server that owns the zone |
| TC | 1 | TrunCation: the reply did not fit in the datagram |
| RD / RA | 1 / 1 | Recursion desired (set in the query) / recursion available (set in the reply) |
| Z, AD, CD | 3 | Originally reserved; AD and CD were later assigned to DNSSEC |
| RCODE | 4 | 0 no error, 1 format error, 2 server failure, 3 NXDOMAIN (no such name), 5 refused |
| QDCOUNT, ANCOUNT, NSCOUNT, ARCOUNT | 16 each | Number of entries in the question, answer, authority and additional sections |
/* dns_query.c — send one DNS query over UDP and inspect the reply header.
usage: ./dns_query 8.8.8.8 www.example.com */
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
static size_t put_name(unsigned char *p, const char *name) { /* www.example.com → 3www7example3com0 */
size_t n = 0;
while (*name) {
const char *dot = strchr(name, '.');
size_t len = dot ? (size_t) (dot - name) : strlen(name);
p[n++] = (unsigned char) len; /* label length (1–63) */
memcpy(p + n, name, len);
n += len;
name += dot ? len + 1 : len;
}
p[n++] = 0; /* the empty root label ends the name */
return n;
}
int main(int argc, char *argv[]) {
unsigned char q[512], r[512]; /* classic DNS-over-UDP limit: 512 bytes */
struct sockaddr_in dns;
struct timeval tv = { 3, 0 }; /* wait at most 3 s for the reply */
uint16_t id = (uint16_t) getpid(); /* any 16-bit value; resolvers randomise it */
size_t len = 12;
ssize_t n;
int fd;
if (argc != 3 || strlen(argv[2]) > 253) { fprintf(stderr, "usage: %s resolver-ip name\n", argv[0]); return 1; }
memset(q, 0, 12); /* 12-byte header */
q[0] = id >> 8; q[1] = id & 0xFF; /* ID, big-endian */
q[2] = 0x01; /* flags 0x0100: standard query, RD = 1 */
q[5] = 1; /* QDCOUNT = 1 */
len += put_name(q + len, argv[2]);
q[len++] = 0; q[len++] = 1; /* QTYPE = 1 (A record) */
q[len++] = 0; q[len++] = 1; /* QCLASS = 1 (IN, Internet) */
fd = socket(AF_INET, SOCK_DGRAM, 0);
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
memset(&dns, 0, sizeof dns);
dns.sin_family = AF_INET;
dns.sin_port = htons(53);
if (inet_pton(AF_INET, argv[1], &dns.sin_addr) != 1) { fputs("bad resolver address\n", stderr); return 1; }
sendto(fd, q, len, 0, (struct sockaddr *) &dns, sizeof dns); /* one datagram = the whole query */
n = recvfrom(fd, r, sizeof r, 0, NULL, NULL); /* one datagram = the whole reply */
if (n < 12) { fputs("no reply within 3 s: a real resolver would retry\n", stderr); return 1; }
if (((r[0] << 8) | r[1]) != id) { fputs("ID mismatch: not our reply\n", stderr); return 1; }
printf("%zd-byte reply, RCODE %d, %d answer(s)%s\n", n, r[3] & 0x0F, (r[6] << 8) | r[7],
(r[2] & 0x02) ? ", TC = 1: retry over TCP" : "");
close(fd);
return 0;
}Matching replies. The client remembers the ID (plus the server's address and port) and drops any reply that does not match. With only 65,536 possible IDs a forger can guess and poison a cache, so after Dan Kaminsky's 2008 attack resolvers also randomise the UDP source port, multiplying the guessing work. Retransmission is the client's job: resolvers wait a few seconds, retry, then move on to the next configured server.
Size limits. RFC 1035 limits a DNS message over UDP to 512 bytes, not counting the IP and UDP headers. EDNS(0) (RFC 2671, now RFC 6891) lets a client advertise a bigger buffer — typically 1,232 to 4,096 bytes — in an OPT pseudo-record, which DNSSEC's large signed answers need. If an answer still does not fit, the server sends what fits with TC = 1 and the client repeats the query over TCP port 53, where every message is preceded by a 2-byte length field because a byte stream has no boundaries of its own. Zone transfers (AXFR, IXFR) always use TCP, and since RFC 7766 (2016) every DNS implementation must support TCP.
Pick UDP when the features it lacks are ones you do not need, or would rather build yourself. The deciding questions: how big is each exchange, does a late packet still matter, must one message reach many receivers, and how small must the implementation be?
| Requirement | Better choice | Why / examples |
|---|---|---|
| A single short request and reply | UDP | No handshake: DNS, NTP, SNMP and RADIUS finish in one round trip |
| Real-time audio, video or games | UDP | A retransmitted packet would arrive too late: RTP for VoIP and video calls, game state updates |
| Broadcast or multicast | UDP | TCP is point-to-point only: DHCP discovery, RIP, mDNS, IPTV multicast |
| A tiny code footprint | UDP | TFTP fits in network-boot firmware (PXE) |
| Huge numbers of clients with no per-client state | UDP | A DNS server keeps no connection table at all |
| Bulk or long transfers that must arrive complete and in order | TCP | File transfer, web pages, e-mail, database sessions, SSH |
| Congestion-friendly behaviour without extra work | TCP | TCP's congestion control comes free; a UDP application must add its own (RFC 8085 gives the guidelines) |
| Easy passage through firewalls and NAT | Usually TCP | Many networks block unknown UDP traffic or forget UDP mappings quickly |
The line keeps moving. QUIC (RFC 9000, 2021) builds reliability, TLS 1.3 encryption and congestion control in user space on top of UDP, and HTTP/3 runs over it on UDP port 443. Choosing UDP therefore does not mean choosing unreliability — it means the application, not the kernel, decides how much reliability it needs, exactly as TFTP (stop-and-wait) and DNS (retry on timeout, fall back to TCP) do.
Try the problem first, then reveal the working one step at a time.
A PXE client reads two files by TFTP (octet mode, 512-byte blocks, no losses): pxelinux.0 of 1,300 bytes and menu.cfg of 1,024 bytes. For each, list the DATA blocks and count every packet, including the RRQ.
A router downloads a 1 MiB (1,048,576-byte) firmware image by TFTP over a path with RTT = 10 ms. Estimate the transfer time and throughput, ignoring transmission time. How much does the blksize option with 8,192-byte blocks help?
A resolver sent a query with ID 0x1A2B. The first 12 bytes of the reply are 1A 2B 81 83 00 01 00 00 00 01 00 00 (hex). Decode them and say what the client should do. What if bytes 2–3 were 83 80 instead?
Choose UDP or TCP and justify: (a) a stock ticker that multicasts prices to 2,000 screens on a LAN; (b) uploading a 4 GB database backup; (c) a thermostat that sends a 20-byte reading every minute; (d) a voice call.
A UDP client calls sendto() three times with 100, 200 and 300 bytes. The server then calls recvfrom() three times. (a) What do the calls return with a 1,024-byte buffer, assuming nothing is lost? (b) With a 150-byte buffer? (c) What could a TCP receiver see after three send() calls of the same sizes?
A client reads a 5,120-byte file by TFTP. (a) How many DATA packets are sent, and what are the last block's number and size? (b) Count all packets if nothing is lost. (c) The ACK for block 4 is lost once, and the server's retransmission timer recovers from it. How many packets are sent now, counting the lost one?
Decode this DNS header (hex): AB CD 81 80 00 01 00 02 00 00 00 00. Is it a query or a response? Was it truncated? How many answer records follow?
The UDP echo server is not running. What does each client experience: (a) the unconnected echo client from this article, with its 2-second timeout; (b) the same client without the timeout; (c) a connected UDP client that calls send() and then recv()?
Write in hex the WRQ packet that uploads r1.cfg in netascii mode, and give its length. What is the server's first reply if it accepts the write, and if a file of that name already exists and may not be overwritten?
recvfrom() returning 0 is a legal empty datagram, not end-of-file — only TCP uses a 0-byte read to say that the peer has closed.10 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.
Modelled on real KPSC questions (reworded) with the same concept and answer; each links to its original paper.