We will now implement a utility to send DNS queries to a DNS server and receive the DNS response.
This should not normally be needed in the field. It is, however, a good opportunity to better understand the DNS protocol and to get experience of sending binary UDP packets.
We begin with a function to print a name from a DNS message.
DNS encodes names in a particular way. Normally, each label is indicated by its length, followed by its text. A number of labels can be repeated, and then the name is terminated with a single 0 byte.
If a length has its two highest bits set (that is, 0xc0
), then it and the next byte should be interpreted as a pointer instead.
We must also be aware at all times that the DNS response from the DNS server could be ill-formed or corrupted. We must try to write our program in such a way that it won't crash if it receives a bad message. This is easier said than done.
The declaration for our name-printing function looks like this...