Experiments and implementations · Intermediate

Observing DNS truncation and TCP fallback

Use a restricted loopback DNS responder to observe a truncated UDP response, retry the same question over TCP and inspect DNS-over-TCP length framing.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. Keep the responder local and deliberately restricted
  2. Return a truncated response instead of a complete answer
  3. Distinguish DNS truncation from IP fragmentation
  4. Frame the body before interpreting it
  5. Record the stage and transport of a failure
  6. Ask Logeia about this articleCheck your understanding

Keep the responder local and deliberately restricted

Bind UDP and TCP to an available port on 127.0.0.1 without changing resolver settings or firewall rules. The responder accepts one fixed A question for demo.example. It is a restricted model, not a general authoritative server or recursive resolver. DNSSEC, caching, EDNS and arbitrary compressed-name decoding are outside its implementation. The objective is to observe a client branch from a truncated UDP response to a TCP retry carrying the same question. Do not request large responses from public infrastructure or send traffic to another user’s service. The loopback scope and fixed input make transport behavior inspectable while avoiding configuration changes or a claim about how every real resolver is implemented.

Return a truncated response instead of a complete answer

The client sends a fixed transaction identifier and question over UDP. The responder returns that question with TC set and without the complete A answer. After checking the identifier and truncation flag, the client connects to the same local port over TCP. DNS messages on TCP carry a two-byte length prefix. Reading that prefix and its body still requires a receive loop because one recv need not return the requested amount. Socket waits are bounded. Validation in this example is intentionally tailored to its fixed exchange; do not reuse it as a production parser for arbitrary responses from an unknown DNS server. Production validation requires additional protocol and security checks.

python
import socket, struct, threading
question = b'\x04demo\x07example\x00' + struct.pack('!HH', 1, 1)
query = struct.pack('!6H', 0x1234, 0x0100, 1, 0, 0, 0) + question
reply_flags = 0x8000 | (struct.unpack('!H', query[2:4])[0] & 0x0100)
def exact(sock, size):
    data = b''
    while len(data) < size:
        part = sock.recv(size - len(data))
        if not part:
            raise EOFError('incomplete DNS frame')
        data += part
    return data
errors = []
with socket.socket() as tcp, socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as udp:
    tcp.bind(('127.0.0.1', 0)); tcp.listen(1); tcp.settimeout(3)
    address = tcp.getsockname()
    udp.bind(address); udp.settimeout(3)
    def serve():
        try:
            data, peer = udp.recvfrom(512)
            assert data == query
            truncated = struct.pack('!6H', 0x1234, reply_flags | 0x0200, 1, 0, 0, 0) + question
            udp.sendto(truncated, peer)
            conn, _ = tcp.accept()
            with conn:
                conn.settimeout(3)
                size = struct.unpack('!H', exact(conn, 2))[0]
                assert exact(conn, size) == query
                answer = (struct.pack('!6H', 0x1234, reply_flags, 1, 1, 0, 0)
                          + question + b'\xc0\x0c' + struct.pack('!HHIH', 1, 1, 60, 4)
                          + socket.inet_aton('192.0.2.1'))
                conn.sendall(struct.pack('!H', len(answer)) + answer)
        except BaseException as error:
            errors.append(repr(error))
    server = threading.Thread(target=serve, daemon=True); server.start()
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as client:
        client.settimeout(3); client.sendto(query, address)
        response, peer = client.recvfrom(512)
        ident, flags = struct.unpack('!HH', response[:4])
        assert peer == address and ident == 0x1234 and flags & 0x0200 and flags & 0x0100
    with socket.create_connection(address, timeout=3) as client:
        client.sendall(struct.pack('!H', len(query)) + query)
        length = struct.unpack('!H', exact(client, 2))[0]
        response = exact(client, length)
        assert struct.unpack('!H', response[2:4])[0] & 0x0100
        assert response[:2] == query[:2] and response[-4:] == socket.inet_aton('192.0.2.1')
    server.join(3)
    assert not server.is_alive() and not errors
    print('UDP TC -> same question over TCP -> 192.0.2.1')

Distinguish DNS truncation from IP fragmentation

TC is a flag in the DNS message; it does not simply report that an IP packet was fragmented. The client also does not continue receiving the remainder of the original UDP reply on TCP. It retransmits the question using TCP and receives another DNS response. This model deliberately creates the condition in which the UDP reply is incomplete. Real response-size behavior also depends on extensions, path conditions and implementation choices. Neither “DNS only uses UDP” nor “TCP is only for zone transfers” explains the observed branch. Follow the application question and response as protocol units separately from how lower layers split, transmit or reassemble their data.

Frame the body before interpreting it

The TCP response contains one A record with documentation address 192.0.2.1. It is not an advertisement of a reachable application service. The client reads the two-byte length and then exactly that many message bytes before checking its fixed expected fields. An empty read during the frame is a termination error, not a complete empty response. Check the response identifier as well as the expected record content. Reconstructing one known message does not test multiplexed questions, general connection management or connection-reuse performance. The restricted response is useful because every byte has a planned interpretation, allowing framing errors to be distinguished from unrelated resolver features.

Record the stage and transport of a failure

Record receiving TC over UDP, sending the same question over TCP and receiving the expected A answer as separate checks. A failed UDP exchange is not the same event as receiving a truncated response. A refused TCP connection also differs from a DNS response saying the name does not exist. This experiment fixes the destination, question, timeout and client implementation. Real troubleshooting may additionally investigate blocked TCP, return paths, response validation and caches. Success on the local model does not establish Internet-wide DNS health or prove how a particular operating-system resolver will recover. Preserve the transport and stage of each observation before choosing the next diagnostic hypothesis.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Understand the systems behind the web · STEP 10

Choose a learning path