/etc/hosts is key file for name resolution in any Linux Unix system. Learn fields, formats within /etc/hosts file. Understand meaning of each field and how it can be set.
This is also one of the important file in Linux-Unix system like /etc/passwd or /etc/fstab. Name resolution in 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 system then it will go for it and then this file dont play much of role in name resolution. Basically this file is static IP lookup table on server.
Its a text file which can be viewed using cat, more, less etc commands. Once can edit this file using text editors like vi. Sample /etc/hosts file is shown as 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
# NTP server
10.10.1.85 ntpsvr1 masterntp
10.10.1.86 ntpsvr2 #standby server
Format being followed is “IP Hostname” where both fields are separated by space or tab and one IP per line. Comments can be added with lines starting with # symbol. Comments can be added on the same line of IP entry too. Any text following # symbol will be ignored till end of line. These lines will be ignored by kernel/shell/program when it reads this file. Those are just comments added for understanding of user (human). Like in above example ‘NTP server’ and ‘standby server’ both are comments.
Hostname can contain only alphanumeric characters, minus sign (-) and period (.) It should always starts with alphabet and ends with alphanumeric character.
There is also an 3rd field in each row which is optional. This field is for aliases. These are short names, alternate names etc for same IP. In above example ‘masterntp’ is alias to IP 10.10.1.85
You will see 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’ hostname and another is that server’s own IP and hostname entry.