Robust way to resolve a DNS address in a script (IPv4 (A) and IPv6 (AAAA))?

Issue

This Content is from ServerFault. Question asked by Amandasaurus

I have a domain name in a bash variable ($TARGET), and I want to get the IPv4 (A record) address of it in my bash script (I also want to get the IPv6 AAAA record (if exists)), in a robust manner.

i.e. What bash/unix command will: (i) print the IP address (and only the IP address) of the DNS resolution (ii) print nothing to stdout (or non-zero exit) if there is no DNS record for that domain found (iii) allow me to choose to ask for A or AAAA record.

host "$TARGET" prints lots of human readable stuff, and I’m reluctant to parse that.

dig +short looked promising, but in some scenarios, it also prints other warning messages which I do not understand, or care about.

$ dig +short -t A "$TARGET"
;; Warning: Client COOKIE mismatch
1.2.3.4

Debian test/bookworm. Bash v5.2 (installed via apt)



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from serverfault, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?