Sub topic 8
DNS: port 53 over UDP and TCP
This chapter assumes you know what an IP address is, how a client talks to a server, and how to run commands in a terminal. You should also be able to read a short Python script. Earlier chapters covered ports, sockets, and the difference between TCP and UDP. Here you apply them to the protocol that nearly every other protocol depends on.
What DNS does and where port 53 fits
The Domain Name System (DNS) is a distributed database that maps names such as example.com to data such as IP addresses. A program that needs to connect to example.com first asks DNS for an address. Only then can it open a TCP connection to port 80 or 443.
DNS servers listen on port 53. The same port number is registered for both UDP and TCP, so a DNS server normally listens on both:
| Transport | Port | Typical use |
|---|---|---|
| UDP | 53 | Ordinary queries and answers that fit in one datagram |
| TCP | 53 | Large answers, zone transfers, and some privacy or policy setups |
The client side uses an ephemeral port, as described in the sockets chapter. A query goes from, say, 192.0.2.50:49812 to 192.0.2.53:53. The reply goes back to 192.0.2.50:49812.
Why UDP is the default
A typical lookup is one small question and one small answer. Setting up a TCP connection costs a three-way handshake before any data moves, and closing it costs more packets. For a single question, that overhead is larger than the question itself.
UDP avoids the setup. The client sends one datagram and waits for one datagram back. DNS handles reliability itself:
- The client sets a timer. If no answer arrives, it retries, often against a second server.
- Each query carries a 16-bit transaction ID. The client matches replies to queries by this ID, together with the source port and the question.
- A server that handles thousands of clients does not keep per-client connection state for UDP queries.
When DNS uses TCP
Three situations push DNS onto TCP.
Truncated responses
The original DNS specification limited UDP messages to 512 bytes. If a server's answer does not fit, it sets the TC (truncated) flag in the reply and sends what fits. The client then repeats the same query over TCP on port 53 and receives the full answer.
Modern clients and servers often use EDNS(0), an extension that lets the client advertise a larger UDP buffer, commonly around 1232 bytes. This reduces truncation but does not remove it. Large answers still occur, especially with DNSSEC signatures, which add substantial data to responses.
Zone transfers
A zone transfer copies all records of a DNS zone from a primary server to a secondary server. The request types are AXFR (full transfer) and IXFR (incremental transfer). They always use TCP, because the data can be large and must arrive complete and in order.
Zone transfers expose every record in a zone. Restrict them to the secondary servers that need them, by IP address or by authentication such as TSIG keys.
Encrypted and policy-driven use
Some resolvers use TCP for all queries, for example to avoid spoofed UDP replies or to meet a policy. DNS over TLS (DoT) is a separate case. It runs over TCP on port 853, not 53, and the TLS chapter covers the pattern. DNS over HTTPS (DoH) rides on HTTPS, so it uses port 443.
DNS roles and which ports they use
Several programs take part in a lookup, and each uses port 53 differently.
- A stub resolver is the small client code inside your operating system. It sends queries to a configured recursive resolver and uses an ephemeral source port.
- A recursive resolver (such as one run by your ISP or company) accepts queries from clients on port 53. To answer them, it sends its own queries to other servers' port 53.
- An authoritative server holds the actual records for a zone and answers on port 53. It does not usually serve arbitrary clients' recursive queries.
This matters for firewalls. A recursive resolver needs inbound port 53 from your clients and outbound port 53 to the whole internet. An authoritative-only server needs inbound port 53 from anywhere, since any resolver may ask it.
Seeing DNS traffic
You can check what a host is listening on with the command from the inspecting chapter:
# Show listening UDP and TCP sockets on port 53
ss -tulnp | grep ':53 'On many Linux systems you will see a local stub such as systemd-resolved bound to 127.0.0.53:53. That address is loopback, so only programs on the same machine can reach it.
To query a server directly and force the transport, use dig:
# Default query (UDP)
dig @192.0.2.53 example.com A
# Force TCP
dig @192.0.2.53 example.com A +tcp
# Ask for a very small UDP buffer to provoke truncation
dig @192.0.2.53 example.com TXT +bufsize=512 +ignoreWith +ignore, dig does not retry over TCP when it sees the TC flag, so you can observe the flag in the output. Use these only against servers you operate or that are open for public use.
Building a DNS query in Python
The next script sends a hand-built DNS query over UDP, so you can see that DNS is just bytes on port 53. It uses only the standard library. Replace the resolver address with one reachable from your network.
import socket
import struct
def build_query(name, qtype=1):
header = struct.pack(">HHHHHH", 0x1A2B, 0x0100, 1, 0, 0, 0)
labels = b"".join(
bytes([len(part)]) + part.encode("ascii")
for part in name.split(".")
)
question = labels + b"\x00" + struct.pack(">HH", qtype, 1)
return header + question
query = build_query("example.com")
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.settimeout(3)
s.sendto(query, ("8.8.8.8", 53))
data, addr = s.recvfrom(512)
flags = struct.unpack(">H", data[2:4])[0]
print("from :", addr)
print("bytes :", len(data))
print("truncated :", bool(flags & 0x0200))
print("rcode :", flags & 0x000F)
print("answers :", struct.unpack(">H", data[6:8])[0])The header is 12 bytes: ID, flags, and four counts. Flags value 0x0100 sets the "recursion desired" bit. The question is the name as length-prefixed labels, ending in a zero byte, followed by the type (1 means an A record) and class (1 means Internet).
The TCP version differs in one respect. A DNS message sent over TCP is preceded by a 2-byte length field, because TCP is a byte stream with no message boundaries:
import socket
import struct
def build_query(name, qtype=1):
header = struct.pack(">HHHHHH", 0x1A2B, 0x0100, 1, 0, 0, 0)
labels = b"".join(
bytes([len(part)]) + part.encode("ascii")
for part in name.split(".")
)
return header + labels + b"\x00" + struct.pack(">HH", qtype, 1)
def recv_exact(sock, n):
buf = b""
while len(buf) < n:
chunk = sock.recv(n - len(buf))
if not chunk:
raise ConnectionError("connection closed early")
buf += chunk
return buf
query = build_query("example.com")
with socket.create_connection(("8.8.8.8", 53), timeout=5) as s:
s.sendall(struct.pack(">H", len(query)) + query)
length = struct.unpack(">H", recv_exact(s, 2))[0]
data = recv_exact(s, length)
print("reply length:", len(data))
print("answers :", struct.unpack(">H", data[6:8])[0])Common errors and gotchas
- Blocking TCP 53. Some firewalls allow only UDP 53 because "DNS is UDP". Small lookups work, but large answers, DNSSEC-signed responses, and zone transfers fail. The symptom is intermittent: some names resolve and others time out.
- Blocking fragments. Large UDP replies may be fragmented at the IP layer. Many networks drop fragments, which makes big UDP responses vanish. This is one reason for smaller EDNS buffer sizes and for the TCP fallback.
- Open resolvers. A recursive resolver reachable from the whole internet can be abused in reflection attacks. A small spoofed query yields a large reply sent to the victim. Limit recursion to your own clients.
- Wrong server for the question. Asking an authoritative server for a name outside its zones returns a refusal, not an answer. Check whether the target is a recursive or an authoritative server.
- Confusing 53 with 853 and 443. Classic DNS is 53. DoT is TCP 853. DoH is 443. Blocking port 53 does not stop clients that use the other two.
- Source port predictability. If a resolver uses a fixed or predictable source port, attackers can more easily forge replies. Resolvers should randomize source ports and transaction IDs.
Summary of key facts
| Item | Value |
|---|---|
| Standard port | 53 |
| Default transport | UDP |
| Fallback transport | TCP, on truncation (TC flag) |
| Always TCP | Zone transfers (AXFR, IXFR) |
| TCP framing | 2-byte length prefix before each message |
| Classic UDP limit | 512 bytes, larger with EDNS(0) |
| DNS over TLS | TCP 853 |
| DNS over HTTPS | TCP 443 |
Exercise
Users report that your company's internal resolver answers small queries, but names with large DNSSEC-signed answers time out. A firewall change last week allowed "DNS" through. What do you check first, and why?
Show answer
Check whether the firewall allows TCP port 53 in addition to UDP port 53. Large signed answers can exceed the UDP size limit, so the server sets the TC flag and the client retries over TCP. If TCP 53 is blocked, the retry fails and the lookup times out, while small answers that fit in UDP keep working. Confirm by running dig +tcp against the resolver and comparing it with a plain dig.
Exercise
In the TCP example, why does the client prefix the query with struct.pack(">H", len(query)), and why does the UDP example not need it?
Show answer
TCP delivers a stream of bytes with no message boundaries, so the receiver needs the 2-byte length to know where one DNS message ends. UDP preserves datagram boundaries, so each datagram is exactly one DNS message and no length field is needed.