Custom DNS Query on Base Linux

There’s no DNS querying tool on the base install of Linux. I’m not a good authority on the history of things like this, but I can say that it has been like this since 2017. I often find the getent features in Linux useful for looking up account data — this tool itself does have a DNS query tool. It requires DNS lookups to log into remote resources by name. This might sound handy, but it has a big limitation — you cannot look up on a custom server. How would one end up in such a situation?! Well if you want to write a script to change the DNS settings on a large number of servers, but only if they can connect to a the new name server — and you don’t want to presume any extra packages are installed you might be left scratching your head. At least I was…

Common tools you might use for this are:

  • dig
  • host
  • nslookup

Conveniently Windows comes with a querying tool (nslookup) — though it’s more in their “domain”.

There’s plenty of blogs and StackExchange answers to tell you all about how these tools work, but not a good answer on how to natively query DNS without installing them.

getent (either ahosts or hosts) brings the user pretty close to the actual DNS query, but it relies on the contents of nsswitch.conf. This file acts to point where to look up for name services. It relies on the databases it points too already existing and being set. So things like /etc/hosts if filled out would be a database — as would be your network interfaces DNS* settings — which is what getent ahosts will use to look for a name/IP.

It’s fascinating that the DNS querying toolset clearly exists in the GNU C libraries and has the capabilities to do lookup against a custom server, but it just hasn’t been implemented.

A workaround?

Ok, it’s Linux — just chuck in the Python one-liner and move on.

python -c 'import socket;print socket.getaddrinfo("www.google.com","http")[0][4][0]'

There’s a problem here — Python socket is just going to load already existing network connect details — it’s not going to make it’s own DNS query. This is no different than what getent is doing.

Perl?

perl -MSocket -E "say scalar gethostbyaddr(inet_aton(\"69.89.27.250\"), AF_INET)"

Same issue. Both Python and Perl have DNS querying modules you can install, but if I’m going to do that I would just install dig.

I could tick through some other languages, but I’m seeing a pattern here. Something to think on.