Linux Hosts File Explained - Syntax and Uses

Linux Hosts File Explained - Syntax and Uses
Page content

Linux hosts File – What Is This?

The purpose of the hosts file is simple – to map hostnames to IP addresses. Its function is the same as the function of the Domain Name System (DNS) but the difference is that unlike DNS, the hosts file is stored locally on the machine. This means that the administrator of the local machine can enter and edit the entries in the hosts file as required.

The hosts file is not unique to Linux. In fact, the hosts file is present in many operating systems, such as UNIX/Linux, the various Windows OS, Mac, Symbian, OS/2, etc. Actually, if an operating system can be used to access the Net, then most likely it has a hosts file. However, the location of the hosts file varies under different operating systems. Under Linux the typical location for the hosts file is in /etc/hosts but this is not an absolute rule for absolutely any Linux distro.

Syntax of the Linux hosts File

The syntax of the Linux hosts file isn’t sophisticated. The format for the hosts file is the same on Linux/UNIX and Windows and it is as follows:

[IP address] [domain name] [alias]

Therefore, if you want to add localhost, here is how the entry will look like:

127.0.0.0 www.mysite.com localhost

It is important to note that /,\, and https:// are omitted. Otherwise, there is nothing special about the syntax of the entries in the Linux hosts file.

If you want to temporarily exclude some entries without deleting them forever, you can comment them out. The sign # is used for that.

The syntax of the Linux hosts file is pretty simple and for a small number of entries, you can use a conventional text editor. However, when you have many entries to input, then automated tools are what you need because they not only speed the process but also reduce the amount of errors.

Uses of the Linux hosts File

Linux hosts file isn’t an obsolete file, as it might look at first. Its basic uses are these:

  • To facilitate network testing. When you need to make a test server behave as if it were a real production server and to test how a particular applications or service performs, the hosts file is perfect for the purpose.
  • To accelerate browsing speed. When your browser doesn’t have to send DNS requests to a remote system, this speed browsing. However, have in mind that when the hosts file is large and/or it doesn’t contain a particular IP. This could seriously slowdown browsing speed.
  • To block adware and other pests. Finally, one more use of the Linux hosts file is to block adware and spyware. Fortunately, malware isn’t such a problem under Linux as it is under Windows but still there are tons of browser adware and spyware that are cross-platform, and because of this you can encounter them under Linux as well. When you add the IPs of such known adware and spyware networks to your hosts file, you won’t be seeing these nuisances.