G27
Self-checkedTier 2 15 min readcn.udp-ports

UDP and ports

The User Datagram Protocol: the 8-byte header, ports and how a host uses them to deliver a datagram to the right process, the checksum with its pseudo header, what UDP does not do (no connection, no retransmission, no ordering, no flow or congestion control), the size limits and fragmentation, and when to choose UDP instead of TCP.

Why it exists

IP delivers a datagram to a host; a host runs many programs. The transport layer must hand each arriving datagram to the right process. UDP does only that, and a checksum, on top of IP: it has no connection set-up, no acknowledgements, no retransmission, no ordering and no congestion control. That makes it small and fast, and it suits a question and an answer (DNS), a one-shot configuration exchange (DHCP), and streams that prefer a late packet lost to a late packet repeated (voice, video). GATE asks about the header fields and their sizes, how the checksum works, what UDP guarantees (nothing), how ports and sockets identify processes, the largest datagram, and which application protocols use UDP.

Prerequisites

You need the TCP segment and the handshake of TCP basics, to contrast it with, and the idea of a port as a transport address.

Precise definitions

Ports. A port number is a 16-bit number (00 to 6553565535) that names a process (strictly, a socket) on a host. A datagram is addressed to an (IP address, port) pair. The ranges:

  • well-known (system) ports, 00 to 10231023: fixed services (DNS 53, DHCP 67 and 68, HTTP 80);
  • registered ports, 10241024 to 4915149151: services registered with the registry;
  • dynamic (ephemeral) ports, 4915249152 to 6553565535: chosen by the operating system for the client side.

TCP and UDP have separate port spaces: UDP port 53 and TCP port 53 are different endpoints (and DNS uses both).

The UDP header is four 16-bit fields, 8 bytes in all:

fieldbitsmeaning
source port16the sender's port (may be 0 if no reply is wanted)
destination port16the receiving process
length16header plus data, in bytes (at least 8)
checksum16over the pseudo header, the header and the data

Then the data. TCP's header, for comparison, is at least 20 bytes.

The checksum. The 16-bit Internet checksum (ones' complement sum, the same algorithm as in IP and ICMP) is computed over the pseudo header (source address, destination address, a zero byte, the protocol number 17 and the UDP length: 12 bytes that are not transmitted), the UDP header with the checksum field set to zero, and the data (padded with a zero byte if its length is odd). The sender sends the complement of the sum. The receiver adds the same words including the checksum: the result must be all ones (0xFFFF), otherwise the datagram is silently discarded. The pseudo header makes the checksum detect a datagram delivered to the wrong host or with the wrong protocol number. In IPv4 the checksum is optional (a sender may transmit 0); in IPv6 it is required. If the computed checksum is 0 it is sent as 0xFFFF, because 0 means "no checksum".

Service. UDP is connectionless (no handshake; each datagram is independent), unreliable (a lost or damaged datagram is not retransmitted and the sender is not told), unordered (datagrams may arrive in a different order), without flow or congestion control, and message-oriented: one sendto is one datagram and one recvfrom returns exactly one datagram (TCP, in contrast, is a byte stream with no boundaries). Reliability, if needed, is built by the application.

Demultiplexing. A UDP socket is identified by the pair (destination IP address, destination port); datagrams from any number of senders with that pair go to the same socket, and the receiver learns the sender's address and port from the datagram. A TCP connection is identified by four values (source address and port, destination address and port), and each connection gets its own socket.

Size. The IPv4 total length is 16 bits, so a UDP datagram is at most 65535−20−8=6550765535 - 20 - 8 = 65507 bytes of data (with a 20-byte IP header and the 8-byte UDP header). A datagram larger than the link's MTU is fragmented by IP and is lost if any fragment is lost; applications that care keep datagrams below the MTU.

Uses. UDP carries DNS (queries and short answers), DHCP, TFTP, SNMP, NTP, RIP and real-time media (RTP), and is the base of newer protocols such as QUIC. TCP carries HTTP, FTP, SMTP, POP3, IMAP, SSH and BGP. A question "which of these uses UDP?" wants those on the first list.

How it works

A datagram, byte by byte: 10.0.0.1:5000 sends the five bytes hello to 10.0.0.2:53.

A UDP datagram, byte by byte: 10.0.0.1:5000 sends 'hello' to 10.0.0.2:53: start

Computed by a script, not typed
fieldbytesvaluemeaning
source port
destination port
length
checksum
data

Step 0

The whole header is four 16-bit fields, 8 bytes. Built with struct.pack; the checksum is computed by the ones' complement rule.

0 / 5
computed by script: messages built byte by byte with struct, protocols simulated; table-icmp-echo also records a real ICMP exchange with this machine's kernel. python3 scripts/gen-cn6-traces.py

The checksum of that datagram, word by word. The pseudo header is added to the sum but never sent.

The UDP checksum of that datagram, word by word: start

Computed by a script, not typed
part16-bit wordsrunning sum
pseudo header: source address
pseudo header: destination address
pseudo header: zero and protocol 17
pseudo header: UDP length
UDP header: source port
UDP header: destination port
UDP header: length
UDP header: checksum (0 while computing)
data 'hello' (padded with a zero byte)
checksum
receiver's test

Step 0

The pseudo header (addresses, protocol, length) is NOT sent; it is included in the sum so that a datagram delivered to the wrong host or with the wrong protocol is detected.

0 / 11
computed by script: messages built byte by byte with struct, protocols simulated; table-icmp-echo also records a real ICMP exchange with this machine's kernel. python3 scripts/gen-cn6-traces.py

The port ranges.

Port numbers: the three ranges and some well-known services: start

Computed by a script, not typed
rangenumbershow manyexamples
well-known (system) ports
registered (user) ports
dynamic (private, ephemeral) ports
total

Step 0

The ranges and the example assignments are quoted from the IANA registry (from memory: verify against the registry); the counts are computed.

0 / 4
computed by script: messages built byte by byte with struct, protocols simulated; table-icmp-echo also records a real ICMP exchange with this machine's kernel. python3 scripts/gen-cn6-traces.py

Demultiplexing five packets from three senders: UDP needs one socket, TCP three connected sockets.

Demultiplexing five packets: UDP and TCP: start

Computed by a script, not typed
packet (source → destination)UDP: delivered toTCP: delivered to
10.0.0.1:5000 → 10.0.0.9:80
10.0.0.2:5000 → 10.0.0.9:80
10.0.0.1:5000 → 10.0.0.9:80
10.0.0.3:6000 → 10.0.0.9:80
10.0.0.2:5000 → 10.0.0.9:80
sockets in use

Step 0

Two senders can use the same source port (5000) as long as their addresses differ; the TCP connection is identified by the whole four-value tuple.

0 / 6
computed by script: messages built byte by byte with struct, protocols simulated; table-icmp-echo also records a real ICMP exchange with this machine's kernel. python3 scripts/gen-cn6-traces.py

Worked examples

EX 1Reading a UDP header, and checking the checksum

Easy

A datagram arrives as the bytes 13 88 00 35 00 0d 94 42 68 65 6c 6c 6f, from 10.0.0.1 to 10.0.0.2. The program decodes the header and adds the pseudo header and the datagram (the receiver's test); then it recomputes the checksum with the checksum field set to zero, and finally flips one bit to show that the test fails.

#include <stdint.h>
#include <stdio.h>
#include <string.h>
 
/* ones' complement sum of 16-bit words (a trailing odd byte is padded with zero) */
static uint32_t add_words(uint32_t sum, const uint8_t *p, int n) {
    for (int i = 0; i < n; i += 2) {
        uint32_t w = (uint32_t)(p[i] << 8) | (i + 1 < n ? p[i + 1] : 0);
        sum += w;
        sum = (sum & 0xFFFF) + (sum >> 16);
    }
    return sum;
}
 
static uint32_t total(const uint8_t *dg, int n) {
    uint8_t pseudo[12] = {10, 0, 0, 1, 10, 0, 0, 2, 0, 17, (uint8_t)(n >> 8), (uint8_t)n};
    return add_words(add_words(0, pseudo, 12), dg, n);
}
 
int main(void) {
    uint8_t dg[] = {0x13, 0x88, 0x00, 0x35, 0x00, 0x0d, 0x94, 0x42, 'h', 'e', 'l', 'l', 'o'};
    int n = (int)sizeof dg;
    printf("source port %u, destination port %u, length %u, data %d bytes, checksum 0x%04X\n", (unsigned)(dg[0] << 8 | dg[1]), (unsigned)(dg[2] << 8 | dg[3]), (unsigned)(dg[4] << 8 | dg[5]), n - 8, (unsigned)(dg[6] << 8 | dg[7]));
    printf("receiver's sum over pseudo header and datagram: 0x%04X -> %s\n", (unsigned)total(dg, n), total(dg, n) == 0xFFFF ? "accepted" : "dropped");
 
    uint8_t copy[sizeof dg];
    memcpy(copy, dg, sizeof dg);
    copy[6] = copy[7] = 0;
    printf("checksum recomputed with the field set to zero: 0x%04X\n", (unsigned)(~total(copy, n) & 0xFFFF));
 
    dg[10] ^= 0x01;                                              /* one flipped bit in the data */
    printf("after flipping one bit: sum 0x%04X -> %s\n", (unsigned)total(dg, n), total(dg, n) == 0xFFFF ? "accepted" : "dropped");
    return 0;
}
source port 5000, destination port 53, length 13, data 5 bytes, checksum 0x9442
receiver's sum over pseudo header and datagram: 0xFFFF -> accepted
checksum recomputed with the field set to zero: 0x9442
after flipping one bit: sum 0x0100 -> dropped

Reading it. The first two 16-bit fields are the ports: 0x1388=50000\text{x}1388 = 5000 and 0x0035=530\text{x}0035 = 53 (DNS). The length 0x000D=130\text{x}000D = 13 includes the 8-byte header, so the data is 5 bytes ("hello"). The pseudo header exists only inside the computation: the sum over it and the datagram is all ones, so the datagram is accepted; recomputing from scratch gives the same checksum, 0x94420\text{x}9442. One flipped bit changes the sum and the receiver drops the datagram without telling anyone.

EX 2Real UDP sockets: boundaries, senders and what a closed port does

Medium

The program (on the loopback) makes one receiving UDP socket and two sending sockets. It sends datagrams of 10, 20 and 30 bytes from the first and 5 bytes from the second, reads four times with recvfrom, then shows what a connected UDP socket sees when it sends to a port where nothing listens (the kernel gets an ICMP port unreachable message and reports it) and what happens to a datagram that is too large.

#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
 
static struct sockaddr_in loopback(unsigned short port) {
    struct sockaddr_in a;
    memset(&a, 0, sizeof a);
    a.sin_family = AF_INET;
    a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    a.sin_port = port;
    return a;
}
 
static unsigned short port_of(int s) {
    struct sockaddr_in a;
    socklen_t len = sizeof a;
    getsockname(s, (struct sockaddr *)&a, &len);
    return a.sin_port;
}
 
int main(void) {
    int rx = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in to = loopback(0);
    if (bind(rx, (struct sockaddr *)&to, sizeof to) != 0) return 1;
    to = loopback(port_of(rx));
 
    int tx1 = socket(AF_INET, SOCK_DGRAM, 0), tx2 = socket(AF_INET, SOCK_DGRAM, 0);
    char buf[100] = {0};
    sendto(tx1, buf, 10, 0, (struct sockaddr *)&to, sizeof to);
    sendto(tx1, buf, 20, 0, (struct sockaddr *)&to, sizeof to);
    sendto(tx2, buf, 5, 0, (struct sockaddr *)&to, sizeof to);
    sendto(tx1, buf, 30, 0, (struct sockaddr *)&to, sizeof to);
    printf("one receiving socket, four datagrams from two senders:\n");
    for (int i = 0; i < 4; i++) {
        struct sockaddr_in from;
        socklen_t len = sizeof from;
        ssize_t n = recvfrom(rx, buf, sizeof buf, 0, (struct sockaddr *)&from, &len);
        printf("  recvfrom returned %zd bytes, sent by sender %d\n", n, from.sin_port == port_of(tx1) ? 1 : 2);
    }
 
    /* a port where nothing listens: bind a socket, note its port, close it */
    int tmp = socket(AF_INET, SOCK_DGRAM, 0);
    struct sockaddr_in dead = loopback(0);
    bind(tmp, (struct sockaddr *)&dead, sizeof dead);
    dead = loopback(port_of(tmp));
    close(tmp);
    int c = socket(AF_INET, SOCK_DGRAM, 0);
    connect(c, (struct sockaddr *)&dead, sizeof dead);
    ssize_t sent = send(c, "x", 1, 0);
    struct pollfd p = {c, POLLIN, 0};
    poll(&p, 1, 1000);
    ssize_t got = recv(c, buf, sizeof buf, 0);
    printf("send to a closed port returned %zd; the next recv returned %zd: %s\n", sent, got, got < 0 ? strerror(errno) : "no error");
 
    static char big[70000];
    ssize_t n = sendto(tx1, big, sizeof big, 0, (struct sockaddr *)&to, sizeof to);
    printf("sending 70000 bytes in one datagram returned %zd: %s\n", n, n < 0 ? strerror(errno) : "sent");
    return 0;
}
one receiving socket, four datagrams from two senders:
  recvfrom returned 10 bytes, sent by sender 1
  recvfrom returned 20 bytes, sent by sender 1
  recvfrom returned 5 bytes, sent by sender 2
  recvfrom returned 30 bytes, sent by sender 1
send to a closed port returned 1; the next recv returned -1: Connection refused
sending 70000 bytes in one datagram returned -1: Message too long

Reading it. The four recvfrom calls return exactly the sizes that were sent, 10, 20, 5 and 30 bytes: UDP keeps the message boundaries, one call per datagram. All four went to one socket although they came from two senders; the receiver tells the senders apart by the source port that recvfrom fills in. UDP did not tell the sender that anything was wrong when it sent to the closed port: send succeeded. The error came afterwards, because the receiving host answered with an ICMP destination unreachable (port unreachable) message, and the kernel reported it on the connected socket as "Connection refused" (an unconnected socket would not see it). An oversize datagram is rejected at once: no UDP datagram can be larger than 65507 bytes.

EX 3The largest datagram, and fragmentation on Ethernet

Medium

What is the largest amount of data in one UDP datagram, and into how many fragments does IP split it on a link with an MTU of 1500 bytes?

#include <stdio.h>
 
int main(void) {
    int max_data = 65535 - 20 - 8;                  /* IPv4 total length minus IP header and UDP header */
    int ip_payload = max_data + 8;                  /* the UDP datagram is the IP payload */
    int per_fragment = (1500 - 20) / 8 * 8;         /* data per fragment, a multiple of 8 bytes */
    int fragments = (ip_payload + per_fragment - 1) / per_fragment;
    int last = ip_payload - (fragments - 1) * per_fragment;
    printf("largest UDP data %d bytes; IP payload %d bytes\n", max_data, ip_payload);
    printf("MTU 1500: %d data bytes per fragment, %d fragments, the last carries %d bytes (%d with its IP header)\n", per_fragment, fragments, last, last + 20);
    return 0;
}
largest UDP data 65507 bytes; IP payload 65515 bytes
MTU 1500: 1480 data bytes per fragment, 45 fragments, the last carries 395 bytes (415 with its IP header)

Reading it. The IPv4 total length (16 bits) limits a packet to 65535 bytes; the IP header takes 20 and the UDP header 8, leaving 65507 bytes of data. The datagram of 65507+8=6551565507 + 8 = 65515 bytes is cut into pieces of 14801480 bytes (the MTU minus the IP header, a multiple of 8): 44 full fragments and a last one of 395 bytes, 45 in all. UDP does not retransmit, so the loss of any one fragment loses the datagram: that is why UDP applications keep their datagrams below the MTU.

EX 4Which statement is true of UDP?

GATE level

UDP guarantees that datagrams arrive in the order sent. False: no ordering. UDP retransmits a lost datagram after a timeout. False: the application must. The UDP length field gives the number of data bytes. False: it counts the header too (8 + data). A UDP checksum covers the pseudo header, the header and the data. True. The pseudo header is sent with every datagram. False: it is only used in the computation. Two UDP sockets on one host may use the same port number if one is TCP and one is UDP. True: the port spaces are separate. A UDP receiver can distinguish two senders that use the same destination port. True, by the source address and port in the datagram. Port numbers have 16 bits, so there are 216=655362^{16} = 65536 of them. True. A UDP header is 8 bytes, a TCP header at least 20. True. The minimum length value in a UDP header is 8: true (a datagram with no data).

Cheat box

Cheat box

  • UDP header: 8 bytes: source port, destination port, length (header + data), checksum, 16 bits each.
  • Checksum: ones' complement sum over pseudo header (12 bytes, not sent) + header + data; receiver's sum == 0xFFFF. Optional in IPv4; 0 is sent as 0xFFFF.
  • Connectionless, unreliable, unordered, no flow or congestion control, keeps message boundaries.
  • Port: 16 bits; well-known 0 to 1023, registered 1024 to 49151, dynamic 49152 to 65535. TCP and UDP ports are separate.
  • UDP socket == (dest IP, dest port); TCP connection == 4-tuple.
  • Largest data: 65535−20−8=6550765535 - 20 - 8 = 65507 bytes.
  • UDP: DNS, DHCP, TFTP, SNMP, NTP, RIP, RTP. TCP: HTTP, FTP, SMTP, POP3, IMAP, SSH, BGP.

Traps and GATE patterns

Connections

UDP is the thin transport layer over IP that TCP improves on at the price of a handshake and delays; DNS sends its queries in single UDP datagrams, and DHCP and RIP use UDP too (ICMP, ARP and DHCP). Programs reach it through the socket interface. A datagram larger than the link MTU is split by IP fragmentation, and the checksum is the same algorithm as in error detection.

PYQs

6 previous year questions from your book. I re-solved each one myself (0 by running or simulating, 6 by reasoning only); the book's key is shown next to my answer. All PYQs

GATE 2025 · MCQQ12 · page 549 of the book
A machine receives an IPv4 datagram. The
protocol field of the IPv4 header has the protocol
number of a protocol X.
Which ONE of the following is NOT a possible
candidate for X?
  • (a)Internet Control Message Protocol (ICMP)
  • (b)Internet Group Management Protocol (IGMP)
  • (c)Open Shortest Path First (OSPF)
  • (d)Routing Information Protocol (RIP)
GATE 2018 · MCQ · 1 markQ44 · page 554 of the book
Match the following:

Field
Length (bits)
P. UDP Header's Port Number
i. 48
Q. Ethernet MAC Address
ii. 8
R. IPv6 Next Header
iii. 32
S. TCP Header's Sequence Number iv. 16

COMPUTER NETWORK
  • (a)P-III, Q-IV, R-II, S-I
  • (b)P-II, Q-I, R-IV, S-III
  • (c)P-IV, Q-I, R-II, S-III
  • (d)P-IV, Q-I, R-III, S-II
GATE 2017 · MCQQ48 · page 555 of the book
Consider socket API on a Linux machine that
supports connected UDP sockets. A connected UDP
socket is a UDP socket on which connect function has
already been called. Which of the following
statements is/are CORRECT?

I. A connected UDP socket can be used to
communicate with multiple peers simultaneously.
II. A process can successfully call connect function
again for an already connected UDP socket.
  • (a)I only
  • (b)II only
  • (c)Both I and II
  • (d)Neither I nor II
GATE 2005 · MCQ · 1 markQ90 · page 562 of the book
Packets of the same session may be routed through
different paths in:
  • (a)TCP, but not UDP
  • (b)TCP and UDP
  • (c)UDP, but not TCP
  • (d)Neither TCP nor UDP
GATE 2013 · MCQ · 1 markQ12 · page 578 of the book
The transport layer protocols used for real-time
multimedia,
file
transfer,
DNS,
and
email
respectively are:

COMPUTER NETWORK
  • (a)TCP, UDP, TCP, and TCP
  • (b)UDP, TCP, TCP, and UDP
  • (c)UDP, TCP, UDP, and TCP
  • (d)TCP, UDP, TCP, and UDP
GATE 2007 · MCQ · 1 markQ19 · page 579 of the book
Which one of the following uses UDP as the transport
protocol?
  • (a)HTTP
  • (b)Telnet
  • (c)DNS
  • (d)SMTP COMPUTER NETWORK

Self-check

Question 1

A UDP header in hex starts 04 d2 00 35 00 20 ab cd. Source port, destination port, number of data bytes?

Show answer

0x04D2=12340\text{x}04D2 = 1234; 0x0035=530\text{x}0035 = 53; length 0x0020=320\text{x}0020 = 32, so 32−8=2432 - 8 = 24 data bytes.

Question 2

What is the pseudo header used for, and is it sent?

Show answer

It is added to the checksum computation (source and destination addresses, protocol, UDP length) to detect misdelivered datagrams. It is not sent.

Question 3

How does a UDP server tell two clients apart if it has only one socket?

Show answer

By the source address and source port reported with each datagram (recvfrom).

Question 4

What is the largest data a UDP datagram can carry over IPv4?

Show answer

65535−20−8=6550765535 - 20 - 8 = 65507 bytes.

Question 5

Which of DNS, SMTP, DHCP, HTTP uses UDP?

Show answer

DNS (for queries) and DHCP. SMTP and HTTP use TCP.

Revision card

One-screen revision

  • Header 8 bytes: ports, length (includes header), checksum. Connectionless, unreliable, unordered, boundaries kept.
  • Checksum over pseudo header + header + data; receiver's sum 0xFFFF; optional in IPv4.
  • Ports 16 bits, ranges 0-1023, 1024-49151, 49152-65535; separate for UDP and TCP.
  • UDP socket by (dest IP, dest port); TCP by the 4-tuple. Max data 65507.
  • UDP: DNS, DHCP, TFTP, SNMP, NTP, RIP, RTP.

References

  • ·Kurose, Ross, Computer Networking: A Top-Down Approach (8th edition), Chapter 3, Section 3.3 (Connectionless transport: UDP) and Section 3.2 (multiplexing and demultiplexing)
  • ·Tanenbaum, Wetherall, Computer Networks (5th edition), Chapter 6, Section 6.4 (The Internet transport protocols: UDP)
  • ·Forouzan, Data Communications and Networking (5th edition), Chapter 14 (User Datagram Protocol)

Verification

The header, the checksum and the receiver's test are built and decoded byte by byte (scripts/cn_t2.py, scripts/gen-cn6-traces.py); scripts/enum-checks/cn_t2_check.py recomputes the checksum as arithmetic modulo 65535 on 3000 random datagrams, checks that every single-bit flip is detected and that a checksum of zero is sent as 0xFFFF, and tests/cn-t2-traces.test.ts re-adds the words of the printed table. The C programs on the page (decoding a header, the checksum, and real UDP sockets on the loopback: boundaries, demultiplexing, the error that an ICMP port-unreachable message causes, an oversize datagram) are compiled and run by npm run verify:c. The port ranges and the list of well-known ports are quoted from the IANA registry from memory (needs verification against the registry); the limit 65507 = 65535 - 20 - 8 and the fragment counts are computed. UDP-Lite and multicast are not covered. Textbook chapter titles are from memory. SECOND PASS (2026-11-02, done by the assistant, not a human check): every Self-check question was solved before the printed answer was read and all agreed; the definitions, worked examples, cheat box and traps were read claim by claim and the numbers re-derived by hand or by a small script (CRC remainders, binomial tail, checksums); long C programs were not re-read line by line (they are compiled and compared by npm run verify:c, and their printed outputs were checked against the prose). No defect found. Status raised to self-checked; verified needs a textbook or human check.

last verified: never

My notes (saved in this browser)