Skip to content
systemcoding.dev
Networking

Implement a DNS Query Client Over UDP

Write a DNS client in C that builds an A query by hand, sends it over UDP, and decodes the reply including name compression, following RFC 1035.

8 min read
Summarize in AI
Flat illustration of network packets crossing between two hosts, with the C, Rust and Linux logos.

Every getaddrinfo call eventually becomes a small UDP datagram to a resolver, and the datagram format is simple enough to build by hand. Writing a DNS client yourself is one of the best exercises in binary protocol work: it has a fixed header, a variable-length name encoding, a compression scheme that jumps backwards in the packet, and a reply you must not trust. This post builds a client in C17 that asks for an A record, sends the query with a UDP socket, and decodes the answer. It follows RFC 1035, the DNS implementation specification, on Linux 6.12 with glibc 2.40. You need the earlier ideas of network byte order and bounds-checked parsing, both covered elsewhere in this series.

The shape of a DNS message

A DNS message, query or response, starts with a 12-byte header, followed by four sections: questions, answers, authority records and additional records. The header holds six 16-bit fields, all in network byte order:

FieldMeaning in a query
IDA number you choose, echoed in the reply so you can match it
FlagsBit 15 is QR (0 query, 1 response); bit 8 is RD, recursion desired
QDCOUNTNumber of questions, normally 1
ANCOUNTNumber of answers, 0 in a query
NSCOUNTNumber of authority records, 0 in a query
ARCOUNTNumber of additional records, 0 in a query

For a plain recursive query the flags value is 0x0100: QR clear and RD set. That asks the resolver to do the full lookup for you instead of replying with a referral.

Encode the name

DNS does not send names as dotted text. It sends each label with a one-byte length in front, and ends the name with a zero byte. The name www.example.com becomes the bytes 03 w w w 07 e x a m p l e 03 c o m 00. A label is at most 63 bytes, and a whole name is at most 255 bytes. The function must reject anything longer, and it must reject an empty label, which would encode a premature zero.

dns_name.cc
#include <stddef.h>
#include <stdint.h>
#include <string.h>

/* Writes the encoded name at out. Returns bytes written, or -1 on error. */
int dns_encode_name(const char *name, uint8_t *out, size_t cap)
{
    size_t pos = 0;

    while (*name) {
        const char *dot = strchr(name, '.');
        size_t len = dot ? (size_t)(dot - name) : strlen(name);

        if (len == 0 || len > 63)
            return -1;
        if (pos + 1 + len + 1 > cap)
            return -1;

        out[pos++] = (uint8_t)len;
        memcpy(out + pos, name, len);
        pos += len;
        name += len;
        if (*name == '.')
            name++;
    }
    if (pos + 1 > cap)
        return -1;
    out[pos++] = 0;
    return (int)pos;
}

Walking the string www.example.com through the loop writes 03 77 77 77, then 07 65 78 61 6d 70 6c 65, then 03 63 6f 6d, then the terminating 00, for 17 bytes in total. The capacity check runs before each write, because the destination is a fixed buffer and the name came from the command line.

Build and send the query

The question section is the encoded name followed by a 16-bit type and a 16-bit class. Type 1 is A (an IPv4 address) and class 1 is IN (the internet).

query.cc
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>

int dns_encode_name(const char *name, uint8_t *out, size_t cap);
int dns_print_answers(const uint8_t *msg, size_t len, uint16_t id);

static size_t build_query(const char *name, uint16_t id, uint8_t *buf, size_t cap)
{
    if (cap < 12)
        return 0;
    memset(buf, 0, 12);
    buf[0] = (uint8_t)(id >> 8);
    buf[1] = (uint8_t)id;
    buf[2] = 0x01;                         /* RD */
    buf[5] = 1;                            /* QDCOUNT = 1 */

    int n = dns_encode_name(name, buf + 12, cap - 12);
    if (n < 0 || (size_t)n + 12 + 4 > cap)
        return 0;

    size_t pos = 12 + (size_t)n;
    buf[pos++] = 0; buf[pos++] = 1;        /* QTYPE  = A  */
    buf[pos++] = 0; buf[pos++] = 1;        /* QCLASS = IN */
    return pos;
}

int main(int argc, char **argv)
{
    if (argc != 3) {
        fprintf(stderr, "usage: %s <name> <server-ip>\n", argv[0]);
        return 2;
    }

    uint8_t query[512], reply[512];
    uint16_t id = (uint16_t)(getpid() & 0xffff);
    size_t qlen = build_query(argv[1], id, query, sizeof query);
    if (qlen == 0) {
        fprintf(stderr, "bad name\n");
        return 2;
    }

    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0) {
        perror("socket");
        return 1;
    }

    struct timeval tv = { .tv_sec = 3, .tv_usec = 0 };
    setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);

    struct sockaddr_in server = { .sin_family = AF_INET, .sin_port = htons(53) };
    if (inet_pton(AF_INET, argv[2], &server.sin_addr) != 1) {
        fprintf(stderr, "bad server address\n");
        return 2;
    }

    if (sendto(fd, query, qlen, 0, (struct sockaddr *)&server, sizeof server) < 0) {
        perror("sendto");
        return 1;
    }

    ssize_t n = recv(fd, reply, sizeof reply, 0);
    if (n < 0) {
        perror("recv");
        return 1;
    }
    return dns_print_answers(reply, (size_t)n, id);
}

The read timeout is not optional. UDP gives no connection and no error when a datagram is lost, so without SO_RCVTIMEO a dropped packet hangs the program forever. A real resolver retries two or three times with a growing delay, and it picks the transaction ID randomly. Using the process ID, as above, is only fine for a demonstration: a predictable ID makes the reply easy for an attacker to forge, so production code takes it from getrandom.

Decode the reply, including compression

Replies compress names to save space. A name in an answer is often not spelled out again. Instead it is a two-byte pointer whose top two bits are 11, and whose remaining 14 bits are an offset from the start of the message where the name continues. The usual case is c0 0c: a pointer to offset 12, which is where the question's name sits.

Following a pointer means reading from elsewhere in the same buffer, and pointers can point at each other. A reply that loops forever is a classic denial of service, so the decoder counts jumps and gives up.

dns_reply.cc
#include <arpa/inet.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>

/* Advances past a name starting at *pos. Returns 0 on success, -1 if malformed. */
static int skip_name(const uint8_t *msg, size_t len, size_t *pos)
{
    size_t p = *pos;

    for (int guard = 0; guard < 128; guard++) {
        if (p >= len)
            return -1;
        uint8_t b = msg[p];
        if (b == 0) {
            *pos = p + 1;
            return 0;
        }
        if ((b & 0xc0) == 0xc0) {          /* pointer: two bytes, ends the name */
            if (p + 2 > len)
                return -1;
            *pos = p + 2;
            return 0;
        }
        if (b > 63 || p + 1 + b > len)
            return -1;
        p += 1 + b;
    }
    return -1;
}

int dns_print_answers(const uint8_t *msg, size_t len, uint16_t id)
{
    if (len < 12)
        return 1;

    uint16_t got_id = (uint16_t)(msg[0] << 8 | msg[1]);
    uint16_t flags = (uint16_t)(msg[2] << 8 | msg[3]);
    uint16_t qd = (uint16_t)(msg[4] << 8 | msg[5]);
    uint16_t an = (uint16_t)(msg[6] << 8 | msg[7]);

    if (got_id != id || !(flags & 0x8000)) {
        fprintf(stderr, "not our reply\n");
        return 1;
    }
    if ((flags & 0x000f) != 0) {
        fprintf(stderr, "server returned RCODE %u\n", flags & 0x000f);
        return 1;
    }

    size_t pos = 12;
    for (uint16_t i = 0; i < qd; i++) {
        if (skip_name(msg, len, &pos) < 0 || pos + 4 > len)
            return 1;
        pos += 4;                          /* QTYPE + QCLASS */
    }

    for (uint16_t i = 0; i < an; i++) {
        if (skip_name(msg, len, &pos) < 0 || pos + 10 > len)
            return 1;
        uint16_t type = (uint16_t)(msg[pos] << 8 | msg[pos + 1]);
        uint32_t ttl = (uint32_t)msg[pos + 4] << 24 | (uint32_t)msg[pos + 5] << 16 |
                       (uint32_t)msg[pos + 6] << 8 | msg[pos + 7];
        uint16_t rdlen = (uint16_t)(msg[pos + 8] << 8 | msg[pos + 9]);
        pos += 10;

        if (rdlen > len - pos)
            return 1;
        if (type == 1 && rdlen == 4) {
            char text[INET_ADDRSTRLEN];
            inet_ntop(AF_INET, msg + pos, text, sizeof text);
            printf("A %s ttl=%u\n", text, ttl);
        }
        pos += rdlen;
    }
    return 0;
}

Run against a resolver for a name that has one A record, the program prints something like the line below. The address and TTL depend on the zone and will differ:

Text
A 192.0.2.80 ttl=3600

Notice what the decoder checks. It confirms the transaction ID and the QR bit before trusting anything, it reads RCODE from the low four flag bits and refuses a failure code such as 3 (NXDOMAIN), and every offset is compared against len before use. The rdlen > len - pos test is the overflow-safe bounds form, the same subtraction pattern used for any length from the wire. The guard counter in skip_name is there for the benefit of later extensions that follow pointers to read a name; here the function only needs to skip, but the loop bound keeps it safe regardless.

Truncation, TCP and size limits

Classic DNS limits a UDP message to 512 bytes, and a server that has more to say sets the TC (truncated) bit, bit 9 of the flags, and sends what fits. The client is expected to retry over TCP, where the message carries a two-byte length prefix, as described in RFC 1035 section 4.2.2. EDNS(0), defined in RFC 6891, lets a client advertise a larger UDP payload size in an OPT record so that fewer answers truncate. The client above ignores both, so it shows a partial answer set as if it were complete when TC is set. Production resolvers handle both.

Reading the reply with a debugger's eye

When your decoder prints nothing, dump the reply in hex and read it against the layout. A typical reply for a single A record begins with the same two ID bytes you sent, then 81 80 for the flags (QR set, RD set, RA set, RCODE 0), then 00 01 00 01 00 00 00 00 for one question and one answer. The question is echoed back verbatim, so the next bytes are the encoded name and the four type and class bytes. The answer then starts with c0 0c, a pointer to offset 12, followed by 00 01 00 01 for type and class, a four-byte TTL, 00 04 for the data length, and the four address bytes.

That sequence is worth memorising because it makes failures easy to classify. If the flags end in 83 the RCODE is 3 and the name does not exist. If they end in 82 the server failed (SERVFAIL), which often means a broken upstream or a validation failure. If the answer count is zero but the code is 0, the name exists with no data of the type you asked for. If the reply is shorter than 12 bytes it is not DNS at all, and something on the path, such as a captive portal or a middlebox, answered instead.

Also remember that you can send the same query to different servers and compare. A mismatch between a public resolver and a local one is a quick way to find split-horizon configuration, a stale cache or a filtering resolver, and it needs nothing more than changing the second command-line argument.

Where this client should not be used

It does no retries, trusts a single server, ignores CNAME chains (a CNAME answer appears with type 5 and is skipped), handles only IPv4 and does no DNSSEC validation. It is a learning tool. For real programs call getaddrinfo, or a library such as c-ares that implements retries, search domains and the rest.

Share

Keep reading

Flat illustration of a microcontroller wired to an LED and a sensor, with the Bluetooth, Nordic Semiconductor and Arm logos.
Embedded

Create a Custom BLE GATT Service on nRF52

Define a custom 128-bit GATT service on nRF52 with Zephyr: characteristic properties, read and write callbacks, notifications through the CCC and MTU limits.

9 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.