• 4

There are several command line utilities to resolve host names (hostdignslookup), 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.)

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.

  • 0
Reply Report

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.

  • 0
Reply Report

This is easily achieved with getent:

getent hosts

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

  • 0
Reply Report