You will need to read RFC1034 and 1035. The DNS protocol is far more complicated than that, you will need far more code to parse it.
First, why not using a specific Java DNS library that surely exists and which can both generate and parse DNS packets? Even if you do not want to use it, reading its source may help you understand how the parse is happening.
Second, and if you really want to to it yourself, you will have to understand the generic format of a DNS packet (with a structure separating the question, the authority part, the answer part, the additional part), see section 4 for DNS packet structure, and then for names specifically, you need to understand "DNS compression", see section 4.1.4 of same RFC.
A name does not appear like this in a DNS packet. Each label (the string between two dots) is encoded on the wire with its length and then the label EXCEPT in some cases where pointers are used to point inside another part of the DNS packet in order never to repeat the same label or sequence of labels.
Finally you will need to not just try to grab any string in the DNS packet. A reply can have a lot of other content, like if you get a CNAME
reply you will get two "strings", that is two domain names, the owner of the record and the associated RDATA. You will need to follow these CNAME
records (if you want to find out the first name requested) and then parse replies of A
and AAAA
requests. You obviously also need to take into account negative replies (NXDOMAIN
) that can happen for any name queried.
As for
i want to read the DNS requests made by the browser
, there is a far easier solution.
Install a recursive nameserver, like unbound
and make sure your browser is pointed to it. Then you will easily see all hostnames in the nameserver logfile.
Also another solution with recent browser versions implementing DoH (DNS over HTTPS): again install a nameserver speaking DoH and configure your browser to point to it (see https://www.internetsociety.org/blog/2018/12/dns-privacy-support-in-mozilla-firefox/ for example for Firefox).