Why does the host command not resolve entries in /etc/hosts?
Solution 1:
The host
program uses libresolv
to perform a DNS query directly, i.e., does not use gethostbyname
.
Most programs, when attempting to connect to another host, invoke the gethostbyname
system call or a similar function. This function obeys the configuration of /etc/nsswitch.conf
. This file has a line which in Ubuntu 12.04 defaults to the following:
hosts: files mdns4_minimal [NOTFOUND=return] dns mdns4
which means that it will first use /etc/hosts
, then fall back to DNS queries.
If you want to perform a host lookup this way, you can do this with getent hosts
. For example:
$ getent hosts serverfault.com
198.252.206.16 serverfault.com
I hope this helps.
Solution 2:
Because the host
utility is exclusively a DNS lookup utility.
Most applications use the library calls getaddrinfo
or gethostbyname
. These libraries interrogate a file called /etc/nsswitch.conf
to determine the lookup priority and policy of how to perform different lookups.
Typically /etc/nsswitch.conf
contains the line
hosts: files dns
Which tells a program to first interrogate /etc/hosts
and then interrogate DNS if unsuccessful.
Since hosts does exclusively DNS lookups it does not peek into /etc/hosts
to do the lookup.
Solution 3:
You will find that dig
and nslookup
behave the same way as host
.
The reason for this is that the purpose of all of these commands is to do DNS lookups, not to look in files.
Most other programs use the operating system's name resolver which consults /etc/nsswitch.conf
and then (if required) /etc/resolv.conf
to decide how to resolve the hostname you are requesting. (This is a simplification, there are other options.) The nsswitch.conf
file usually puts precedence on local files rather than DNS.