Linux command line utility to resolve host names using /etc/hosts first

There are several command line utilities to resolve host names (host, dig, nslookup), however they all use nameservers exclusively, while applications in general look in /etc/hosts first (using gethostbyname I believe).

Is there a command line utility to resolve host names that behaves like a usual application, thus looking in /etc/hosts first and only then asking a nameserver?

(I am aware that it would probably be like 3 lines of c, but I need it inside of a somewhat portable shell script.)


Solution 1:

This is easily achieved with getent:

getent hosts 127.0.0.1

getent will do lookups for any type of data configured in nsswitch.conf.

Solution 2:

One tool that would work is getent. So you could use getent hosts www.google.com, or getent hosts localhost. It will retrieve entries from the databases as specified in your Name Service Switch configuration /etc/nsswitch.conf.

For more modern implementations use getent ahosts www.google.com which will get multiple results.

Solution 3:

You can use a gethostbyname() (deprecated) wrapper like:

python -c 'import socket;print socket.gethostbyname("www.google.com")'

Or a getaddrinfo() wrapper like:

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

For python3:

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

Note that getaddrinfo will return all instances as a list. The last part of the command selects only the first tuple. This can also return IPv6 addresses.