job.answiz.com
  • 4
Votes
name

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 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.

  • 0
Reply Report

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]'

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 127.0.0.1

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

  • 0
Reply Report