Sub topic 3
TCP and UDP: which protocols use which
This chapter assumes you know what a port number identifies and the three port ranges. It also assumes you can read short Python scripts and run commands in a terminal. It covers how the two transport protocols differ, why an application protocol picks one, and which common protocols use which.
Two transports, one port space
TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) both sit above IP and both use 16-bit port numbers. Their port spaces are separate. TCP port 53 and UDP port 53 are different endpoints, and a service can listen on one, the other, or both.
The two protocols make different promises:
| Property | TCP | UDP |
|---|---|---|
| Connection setup | Three-way handshake before data | None |
| Unit of data | Byte stream, no message boundaries | Datagram, boundaries preserved |
| Delivery | Retransmits lost segments, delivers in order | Best effort, may be lost, duplicated or reordered |
| Flow and congestion control | Built in | None, the application must handle it |
| Per-packet overhead | 20-byte header minimum | 8-byte header |
| Typical cost | Extra round trips, per-connection state | Almost none |
The application protocol decides which promises it needs. The transport does not know what the bytes mean.
How a protocol chooses
Protocols tend to choose TCP when losing or reordering data would corrupt the result. They choose UDP when a small request and reply fits in one packet, or when a late answer is worse than a missing one.
- Reliability matters most. Web pages, email, file transfer, remote shells and database sessions need every byte in order. They use TCP.
- Small request and reply. A DNS lookup or an NTP time query fits in one datagram each way. A TCP handshake would triple the round trips for no gain, so these use UDP. The client retries if no answer arrives.
- Timeliness beats completeness. Voice, video and games use UDP because a retransmitted packet arrives too late to be useful.
- Broadcast or multicast. TCP is strictly point to point. DHCP clients have no address yet and must broadcast, so DHCP uses UDP.
This is a heuristic, not a rule. The next sections show where it bends.
Common protocols and their transports
| Protocol | Port | Transport | Why |
|---|---|---|---|
| HTTP | 80 | TCP | Reliable page and API transfer |
| HTTPS | 443 | TCP, and UDP for HTTP/3 | HTTP/3 runs over QUIC, which is built on UDP |
| DNS | 53 | UDP and TCP | UDP for queries, TCP for large answers and zone transfers |
| SSH | 22 | TCP | Interactive, ordered session |
| Telnet | 23 | TCP | Same reasons as SSH, but unencrypted |
| SMTP | 25 | TCP | Reliable mail relay |
| POP3 | 110 | TCP | Mail retrieval |
| IMAP | 143 | TCP | Mail retrieval |
| FTP | 21 | TCP | Control channel, plus separate data connections |
| TFTP | 69 | UDP | Tiny stop-and-wait protocol, used for boot files |
| DHCP | 67 and 68 | UDP | Client has no IP address yet and uses broadcast |
| NTP | 123 | UDP | Small timestamp exchange |
| SNMP | 161 | UDP | Short polling requests |
| Syslog | 514 | UDP, often TCP too | Fire-and-forget log lines |
| LDAP | 389 | TCP, UDP for some AD uses | Directory queries |
| SMB | 445 | TCP | File sharing |
| RDP | 3389 | TCP, and UDP as an optional extra | Remote desktop |
Seeing the difference in code
The stream-versus-datagram difference is the one that most often surprises people. This script runs both cases on the loopback interface. It needs no network access.
import socket
# UDP: each sendto() is one datagram, and boundaries are preserved.
rx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rx.bind(("127.0.0.1", 0)) # port 0 asks the OS for a free port
tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
tx.sendto(b"hello", rx.getsockname())
tx.sendto(b"world", rx.getsockname())
first, _ = rx.recvfrom(1024)
second, _ = rx.recvfrom(1024)
print("UDP:", first, second)
tx.close()
rx.close()
# TCP: a byte stream. Two sends can arrive as one read.
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(("127.0.0.1", 0))
srv.listen(1)
cli = socket.create_connection(srv.getsockname())
conn, _ = srv.accept()
cli.sendall(b"hello")
cli.sendall(b"world")
cli.close() # signals end of stream to the peer
data = b""
while True:
chunk = conn.recv(1024)
if not chunk: # empty read means the peer closed
break
data += chunk
print("TCP:", data)
conn.close()
srv.close()The UDP side prints b'hello' b'world': two sends, two receives. The TCP side prints b'helloworld', because TCP keeps no record of where one send ended. Any protocol built on TCP must mark its own message boundaries. HTTP does this with headers such as Content-Length. Protocols built on UDP get boundaries for free but must handle loss themselves.
Protocols that use both
Several protocols use both transports, and each has its own reason.
DNS
A resolver sends queries over UDP port 53. If the answer is truncated, the server sets the TC flag and the client retries over TCP port 53. Zone transfers between name servers use TCP. Modern DNS with large responses (DNSSEC, for example) hits the TCP fallback more often. A firewall that allows only UDP 53 causes intermittent failures that are hard to diagnose.
HTTP/3
HTTP/1.1 and HTTP/2 use TCP 443. HTTP/3 uses QUIC, which runs over UDP 443. QUIC reimplements reliability, ordering and encryption in user space. A browser usually learns about HTTP/3 support from a response header and falls back to TCP if UDP is blocked. Allowing only TCP 443 still works, but you lose HTTP/3.
FTP
FTP uses TCP on both channels, but its structure is unusual. Port 21 carries commands. Each file transfer or directory listing opens a separate data connection, from server port 20 in active mode, or to a server-chosen high port in passive mode. This is why FTP is awkward for firewalls.
Gotchas
- A listening TCP port does not imply the UDP port is open. Check each transport separately.
- UDP scans are ambiguous. A closed UDP port may return an ICMP "port unreachable" message. An open one often returns nothing. Silence can mean open, filtered, or a service that ignored your probe.
- UDP amplification. Services such as DNS, NTP and SNMP answer small spoofed requests with larger replies. Attackers use open servers to flood a victim. Do not expose these services to the internet unless you intend to, and restrict who can query them.
- UDP has no handshake, so source addresses are easy to forge. TCP's handshake makes this much harder.
- Stateful firewalls track UDP "connections" by timeout. They remember a UDP request for a short time so the reply can pass. A slow reply may be dropped after the timeout.
- Do not guess the transport from the port name. The services database lists many ports as both TCP and UDP even when only one is used in practice.
You can check what your system lists:
import socket
for name in ("domain", "ntp", "tftp", "syslog"):
for proto in ("tcp", "udp"):
try:
print(name, proto, socket.getservbyname(name, proto))
except OSError:
print(name, proto, "not listed")The output depends on your services file, such as /etc/services on Linux. The ntp name is listed for UDP on most systems, and syslog is typically UDP-only there.
Checking transports on your own host
List listening sockets for both transports with ss:
ss -tulnpThe -t flag shows TCP and -u shows UDP. A line such as udp UNCONN 0 0 0.0.0.0:123 shows an NTP service. TCP listeners show LISTEN, while UDP sockets show UNCONN, since UDP has no connection state.
Exercise
A new in-house service sends a 40-byte sensor reading once per second to a collector. Occasional lost readings are acceptable, and readings are never retransmitted. Which transport fits best, and what must you do if the collector has to tell two readings apart when they arrive in one network burst?
Show answer
UDP fits best. Each reading is a small independent message, a retransmitted old value has no use, and UDP avoids handshake and per-connection state. UDP preserves datagram boundaries, so two readings arrive as two separate receives. With TCP they could merge into one read and you would need your own framing. You would still add a sequence number or timestamp inside each reading so the collector can detect loss and reordering.
Exercise
Users report that some DNS lookups for large records hang, while small ones work. Your firewall allows inbound and outbound UDP 53 but not TCP 53. What is the likely cause, and what is the fix?
Show answer
Large responses do not fit in a UDP reply, so the server truncates them and sets the TC flag. The client then retries over TCP port 53, which the firewall blocks. Allow TCP 53 as well as UDP 53 for the DNS servers involved.
Exercise
Name two reasons DHCP uses UDP rather than TCP.
Show answer
A DHCP client has no IP address when it starts, so it must broadcast its request, and TCP does not support broadcast. A TCP connection also needs both endpoints to have usable addresses for the handshake. A small request and reply exchange gains little from TCP's setup cost.