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

Solution 1:

This is easily achieved with getent:

getent hosts

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, 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 which will get multiple results.

Solution 3:

Use getent ahosts, for instance:

$ getent ahosts | sed -n 's/ *STREAM.*//p'

You'll get all IPv4 and IPv6 addresses, via the glibc resolver (thus using /etc/hosts first, as usually configured in /etc/nsswitch.conf).

Do not use getent hosts, as it will give you either IPv6 or IPv4 addresses (not both), and the chosen protocol may not be one that does not work. Indeed, IPv6 addresses are generally preferred, but at some places, IPv6 data are filtered (not supported) by the routers.

Solution 4:

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

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

Or a getaddrinfo() wrapper like:

python -c 'import socket;print socket.getaddrinfo("","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.

Solution 5:

resolveip will do this.

Oddly, it's part of the mysql-server packages on RHEL and Ubuntu.