The usefulness of getent

It appears that if you want to do dns lookups, the output of host is a pain to parse, and dig doesn't follow the systems normal search path. So, the solution is to use getent ahostsv4 <hostname> which has easier to parse output (if you're only looking for v4 addresses).

Apparently this is not a well known thing, so I thought I'd drop it here to tell the world :)

Posted: 2013-09-18 19:37 in Tech | permalink | Comments: 9

Elessar - 2013-09-18 20:21

Plus one. Once, I had to write a C program to do that, before I realized getent already did the job. :-)

Chris Boot - 2013-09-18 21:09

It seems you can also use 'ahostsv6' for the IPv6 version, or just 'ahosts' for both. Very useful indeed!

Philipp Kern - 2013-09-18 21:19

What's that? v4? Legacy IP?

Hans - 2013-09-18 22:57

Can you state what is wrong with dig? There is a difference between dig and getent, a big difference. One is for querying only DNS and the other for NSS where DNS may be a part of.

Franklin Piat - 2013-09-19 05:16

nice tip. did you try this: dig +short +search thehost

Richard Smith - 2013-09-19 12:57

The problem with 'dig +short +search foo' is that it tries to be too clever by guessing whether 'foo' is intended as a type, class or host. In particular, it's common to have a host called; but even if is in my search path, 'dig +short +search mx' will treat 'mx' as an rrtype rather than a host. It turns out that 'dig +short +search -q foo' fixes that, but I didn't know about that yesterday.

Douglas - 2013-09-20 12:26

Be careful though -- getent uses the nameservice libraries, so the result might be different from a simple DNS-lookup! e.g. most setups have hosts: files dns in /etc/nsswitch.conf, thus the content of /etc/hosts will be checked before "falling back" to DNS.

Brett Parker - 2013-09-20 12:34

In this case, that was also exactly part of the behaviour required.

Jon - 2013-09-23 21:54

getent is also useful if you want to honour /etc/hosts (and your nss is set up that way) over DNS, or to get passwd-format lines out of e.g. LDAP (getent passwd foo)