Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 79 ยท Transport Layer

UDP

Learn the User Datagram Protocol: the 8-byte header, the checksum with its pseudo-header, loss and reordering, and why DNS, games and QUIC choose UDP. Live code.

The User Datagram Protocol (UDP) is the simplest transport protocol in the Internet suite, defined in RFC 768 in 1980 on a document that fits on one page. It adds just enough to IP to be useful to applications: port numbers (so data reaches the right program) and an optional checksum (so damaged data can be detected). It does not set up a connection, does not acknowledge anything, does not retransmit, does not order the data and does not slow down when the network is congested.

That sounds like a poor deal until you see what it enables. Because UDP does so little, applications can build exactly the behavior they need on top of it, with no handshake delay and no waiting for lost packets. Names of websites are resolved with it, voice calls travel over it, and the newest version of HTTP is built on it through QUIC. This lesson shows the header, the checksum and how an application lives with an unreliable service.

The UDP header

A UDP datagram is an 8-byte header followed by the payload. The header has four 16-bit fields:

Field Size Meaning
Source port 2 bytes Sender's port; may be 0 if no reply is expected
Destination port 2 bytes Receiver's port
Length 2 bytes Header plus payload, in bytes (minimum 8)
Checksum 2 bytes Error detection over header, payload and a pseudo-header
flowchart LR
    subgraph H["UDP header (8 bytes)"]
      direction LR
      SP["Source port<br/>16 bits"] --- DP["Destination port<br/>16 bits"] --- LEN["Length<br/>16 bits"] --- CS["Checksum<br/>16 bits"]
    end
    H --> P["Payload (application data)"]

Compare this with the 20-byte minimum TCP header: UDP has no sequence numbers, no acknowledgments and no window.

The length field is 16 bits, so a UDP datagram can be at most 65,535 bytes in total, and in practice about 65,507 bytes of payload for IPv4 (after the 8-byte UDP and 20-byte IP headers). Large datagrams are fragmented by IP (see the IPv4 packet lesson), and when any fragment is lost the whole datagram is lost. That is why applications keep datagrams below the path MTU, often around 1200 to 1472 bytes, so each fits in one packet.

The checksum

The checksum catches corruption in transit. The sender computes the ones' complement sum of all 16-bit words in the datagram, then takes the ones' complement of the result. The receiver adds all the words again, including the checksum, and the result must be all ones (0xFFFF) if nothing changed.

What makes the UDP checksum special is the pseudo-header. The sum also covers a few fields that are not in the UDP header at all but come from the IP header: the source address, the destination address, a zero byte, the protocol number (17) and the UDP length. This protects against a datagram being delivered to the wrong host or by the wrong protocol, even though the error is not in the UDP bytes themselves.

In IPv4 the checksum is optional: a sender may put zero in the field to say "not computed". In IPv6 it is mandatory, because IPv6 has no header checksum of its own. If the computed value is zero, the sender transmits 0xFFFF instead, since zero means "no checksum". A datagram with a bad checksum is silently discarded and the application never learns about it.

The Python program below builds a real UDP datagram, computes its checksum with the pseudo-header, parses it back and then flips a single bit.

Python Build a UDP datagram and verify its checksum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the raw bytes from the left: c0 00 is source port 49152, 00 35 is destination port 53 (DNS), 00 12 is the length 18 (8 header bytes plus 10 payload bytes), then the checksum and the text. The checksum is only 16 bits, so it is a weak guard: some multi-bit errors cancel out. Link layers add stronger CRCs, and applications that care add their own hashes or use encryption.

What UDP does not do

An application that uses UDP must know what it is not getting:

  • No delivery guarantee. A datagram can be lost to a congested router queue, a bad link or a firewall. Neither sender nor receiver gets a notification.
  • No ordering. Two datagrams sent in order can arrive in the opposite order if they took different paths.
  • No duplicate protection. Rarely, a datagram arrives twice.
  • No congestion control. A UDP sender can transmit at full speed into an overloaded network. Well-behaved applications add their own rate limits, and QUIC brings its own congestion control. This is also why UDP is popular for flooding attacks.
  • No byte stream. Each send produces exactly one datagram and each receive returns exactly one datagram. Message boundaries are preserved, which is the opposite of TCP's byte stream.

Loopback hides most of this: a datagram to your own machine rarely gets lost or reordered. On real networks, assume it will happen. The simulation below sends twenty numbered updates through a randomly lossy network (with a fixed random seed so you get the same result every time) and shows what the receiver sees.

Python Loss and reordering of datagrams

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Seven of twenty updates vanished and one arrived late. The game does not care: it numbers its updates, drops any that are older than the newest one it has applied, and the next update corrects the position anyway. Retransmitting old positions, which is what TCP would do, would only make things worse, because the data is already out of date when it arrives. This pattern is the reason to choose UDP.

Sending and receiving datagrams

The programming model matches the protocol: there is no connection, you just send to an address. The Node.js program below runs an echo server and a client on loopback with the dgram module. Note that the server learns who sent each datagram from the rinfo object that arrives with it, and that message sizes stay exactly as sent.

Node.js A UDP echo server on loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last line shows an important quirk: sending to a closed port does not fail. The send call only reports that the operating system accepted the datagram. On a real network the destination may answer with an ICMP "port unreachable" message (see ICMP), and some systems pass that on as an error on a later call, but you cannot rely on it. The only certain way to know a UDP message arrived is for the application to send an answer, and to use a timeout and retry if the answer does not come.

When to choose UDP

UDP is the right foundation when at least one of these is true:

  • Small request, small response. DNS queries are one datagram each way. A TCP handshake would add a full round trip before the query could even be sent. (DNS switches to TCP for large responses; see DNS.)
  • Timeliness beats completeness. Voice and video calls, live streaming, online games and sensor telemetry are worthless when late. Old data is better skipped than waited for.
  • The application wants its own rules. QUIC, the transport under HTTP/3, runs over UDP so it can implement streams without head-of-line blocking, faster handshakes and encryption in user space, free from the operating system's TCP (see QUIC and modern transports).
  • One-to-many delivery. Broadcast and multicast (previous lesson) work only with connectionless transport, since a single sender cannot keep a connection with every receiver. DHCP and mDNS use this.
  • Simple, stateless services. NTP, SNMP and syslog trade reliability for tiny cost per message.

It is the wrong choice when you simply need all the data in order and do not want to write reliability yourself. A file transfer over raw UDP would have to reinvent sequence numbers, acknowledgments, timers and congestion control, and TCP has already solved those problems.

If you use UDP for anything important, add at least a sequence number so you can detect loss and reordering, a timeout with a limited number of retries, and a limit on your sending rate. Without those three, your program is a poor copy of TCP, or a danger to the network.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How large is the UDP header, and which fields does it contain?

    UDP has four 16-bit fields, 8 bytes in total. Sequence numbers, acknowledgments and windows belong to TCP.
  2. 2. Why does the UDP checksum include a pseudo-header with the IP addresses?

    The pseudo-header (source and destination IP, protocol 17, UDP length) is included in the sum but not transmitted, so misdelivered or misrouted datagrams fail verification.
  3. 3. A sender transmits datagrams 1, 2 and 3. The receiver sees 1, 3, 2. Which statement is true?

    UDP provides no ordering. Datagrams can take different paths. An application that cares must number them and handle out-of-order arrival.
  4. 4. A program calls send() on a UDP socket to a port where nothing listens, and send() reports success. What does that mean?

    UDP has no acknowledgments. A successful send only means the datagram left the application. Delivery needs a reply from the application at the other end.
  5. 5. Which application is the weakest fit for plain UDP without extra reliability?

    File transfer needs every byte in order. Plain UDP would force you to rebuild TCP's reliability and congestion control. The other three tolerate or avoid retransmission.

Summary

  • UDP adds only ports, a length and an optional checksum to IP: an 8-byte header, no connection, no retransmission, no ordering, no congestion control.
  • The checksum covers the UDP header, the payload and a pseudo-header with IP addresses; it is optional in IPv4 and mandatory in IPv6. Bad datagrams are dropped silently.
  • Each send is one datagram and message boundaries are preserved; datagrams larger than the path MTU get fragmented and are best avoided.
  • Loss, duplication and reordering are normal; applications number messages, use timeouts and retries, or simply ignore stale data.
  • UDP fits small request-response exchanges (DNS), real-time media and games, multicast and QUIC.
  • If you need reliable ordered delivery, use TCP.

Next, see how TCP builds a reliable stream and opens connections in TCP Segments and the Three-Way Handshake.