Operating systems like Windows, Linux, MacOS, etc. use the hosts file in order to store domain name/hostname IP relations. Simply the hosts file is used like a local DNS server where the hostnames resolved into IP addresses. These operating systems follow hosts file -> local DNS cache -> DNS server in order to resolve the domain name into IP address. So the hosts file is important which is the first step to resolve domain names.
Display hosts File
The hosts file is located as /etc/hosts. The content of the hosts file is just simple text and can be easily displayed with the cat command via a command-line interface like below.
$ cat /etc/hosts
127.0.0.1 localhost 127.0.1.1 ubuntu The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters
Also text editors can be used to display hosts file content.
hosts File Structure
The hosts file is very simple where it consist of at least two column for each line. Each line contains a single record about IP address and domain name. First the IP address is provided and domain name is provided later. The IP address and domain name is separeted with single or more spaces. Also tab can be used for separation.
127.0.0.1 localhost mylocalhost 127.0.1.1 ubuntu 184.108.40.206 google.com The following lines are desirable for IPv6 capable hosts ::1 ip6-localhost ip6-loopback fe00::0 ip6-localnet ff00::0 ip6-mcastprefix ff02::1 ip6-allnodes ff02::2 ip6-allrouters
In the first line 127.0.0.1 is the IP address of the localhost. Syntax of the hosts file is like below.
IPAddress DomainName DomainAlias
- IPAddress is the IPv4 or IPv6 IP address of the specified DomainName or DomainAlias. This is required.
- DomainName is the domain name related with the IPAddress. This is required.
- DomainAlias is the extra domain definition which is also related with the IPAddress. This is optional.
Edit hosts File
The hosts file is important file as it acts like a DNS server and different domain names can be associated with different IP addresses. So in order to edit hosts file root privileges are required which can be provided by opening the /etc/hosts file as root or using the sudo command.
sudo nano /etc/hosts
Add IP and Related Domain/Host Name
Lets add a record to the /etc/hosts file. We will create a record for the linuxtect.com domain name for the IP address 192.168.1.1 .
We can also add some subdomain for the existing domain.
Add Alias To Hosts File
Alias is optional part of the hosts file record. Alias is just a place holder for the existing IP address – domain name record. But the alias can be used like a domain name.
192.168.1.1 linuxtect.com linuxtect mylinuxtect
Check/Ping Host File Entry
The added host file entry can be easily checked by using the ping command. Just use the domain name or alias for the ping.
192.168.1.1 linuxtect.com linuxtect