What's the cleanest way to do a hostname lookup on a Linux system, that checks /etc/hosts first? [duplicate]

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.

Solution 4:

Use getent ahosts, for instance:

$ getent ahosts www.google.com | sed -n 's/ *STREAM.*//p'
216.58.210.196
2a00:1450:4006:803::2004

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 5:

resolveip will do this.

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