/etc/hosts is a key file for name resolution in any Linux Unix system. Learn fields, formats within /etc/hosts file. Understand the meaning of each field and how it can be set.
This is also one of the important files in the Linux-Unix system like /etc/passwd or /etc/fstab. The name resolution in the Lx-Ux system is being handled by this file. Whenever kernel needs to resolve some hostname to IP, it will search for it in /etc/hosts file. If DNS is configured on the system then it will go for it and then this file doesn’t play much of role in name resolution. Basically this file is a static IP lookup table on the server.
It’s a text file that can be viewed using
less, etc commands. One can edit this file using text editors like
/etc/hosts file is shown below :
# cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 ::1 localhost localhost.localdomain localhost6 10.10.1.64 server34 #This server # Test servers 10.10.1.12 test01 10.10.1.121 test02 # NTP server 10.10.1.85 ntpsvr1.kerneltalks.com ntpsrv1 10.10.1.86 ntpsvr2.kerneltalks.com #standby server
The format being followed is
<IP> <FQDN> <alias> where both fields are separated by space or tab and one IP per line. Comments can be added with lines starting with the
# symbol. Comments can be added on the same line of IP entry too. Any text following the
# symbol will be ignored until the end of the line. These lines will be ignored by the kernel/shell/program when it reads this file. Those are just comments added for the understanding of the user (human). Like in the above example
NTP server and
standby server both are comments.
The hostname can contain only alphanumeric characters, minus sign
- and period
. It should always start with the alphabet and ends with an alphanumeric character.
There is also the 3rd field in each row which is optional. This field is for aliases. These are short names, alternate names, etc for the same IP. In the above example,
ntpsrv1 is an alias to
You will see a couple of entries in all
/etc/hosts file on your environment. Most of them are loopback address i.e. 127.0.0.1 which will be pointing to
localhost and another is that server’s own IP & hostname entry.