A DNS message body can contain questions, answers, or both. For our example, let’s start with questions. A question has this shape:

DNS resource record structure showing a domain name 'elixir-lang.org' (QNAME) with type field 0x00 0x01 (QTYPE) indicating 'A' record, and class field 0x00 0x01 (QCLASS) indicating 'Internet addresses'.

The QNAME is a sequence of strings representing each component of the domain name. Components are just the parts between dots: elixir-lang and org in our example. QTYPE specifies what record type we’re interested in, such as A or AAAA. A is encoded as <<00, 01>>. QCLASS is for the class of the query. We don’t have to pay attention to this, since we can just use <<00, 01>>, which stands for Internet addresses.

We have to take a short detour to look into how strings are encoded. Each string in a sequence of strings is encoded as follows:

  • One byte for the length of the string
  • Followed by the bytes of the string itself

The sequence terminates with a single null byte, 0. Encoding strings in Elixir can be a one-line function. Here, we take a list of strings and return some iodata:

def encode_strings(strings) when is_list(strings) do
  [Enum.map(strings, &[byte_size(&1), &1]) | [0x00]]
end

We’ll ask the DNS server about elixir-lang.org, so let’s see how we’d encode that.

def encode_strings(strings) when is_list(strings) do
  [Enum.map(strings, &[byte_size(&1), &1]) | [0x00]]
end

That looks like just a bunch of bytes, but we can easily break it down. ?e is Elixir syntactic sugar for the byte value of the e ASCII character, 101. The preceding binary is the same as this:

<<_length = 11,
  ?e, ?l, ?i, ?x, ?i, ?r, ?-, ?l, ?a, ?n, g,
  _length = 3,
  ?o, ?r, g,
  0>>

Self-explanatory enough. Looks like we’re ready to send our first query! Ah, but that involves the network. Let’s put a pin in that and finish off our protocol exploration by looking at DNS answers. Don’t worry, it’ll be pretty short.

A DNS answer is similar to a question, but it has a few more fields. Its shape is this:

  • A NAME, TYPE, and CLASS. These are exactly the same as their QNAME, QTYPE, and QCLASS counterparts. NAME is encoded just like QNAME, too.

  • TTL is an integer that represents the Time To Live of the record, expressed in seconds.

  • RDLENGTH is the length, in bytes, of the next field (RDATA).

  • RDATA is for additional record data.