The /etc/hosts file is simply a plain text system file that allows you to map hostnames to IP addresses on your computer. It can be especially useful when you're working on a website or server and need to test it on your local machine before it goes live, or when you want to access a specific server within your network by its hostname rather than its IP address.
To create or edit the /etc/hosts
file on a Linux, Unix, or MacOS system, you will need to use a text editor with root privileges.
For example, to create or edit the /etc/hosts
file using the nano editor, you would open the terminal and enter the following command:
sudo nano /etc/hosts
This will open the /etc/hosts
file in the nano editor, and you can then make any necessary changes.
On a Windows system, you can create or edit the C:\Windows\System32\drivers\etc\hosts
file using a text editor such as Notepad or WordPad. To open the file in Notepad, you will need to run the program as an administrator. To do this, right-click on the Notepad icon and select "Run as administrator" from the context menu.
It's important to note that the /etc/hosts
file is a system file, and making changes to it should be done carefully. It's a good idea to make a backup of the file before making any changes, and to be sure to follow the correct syntax when adding new entries.
Here are some examples of how you might use the /etc/hosts
file:
# Test a website on your local machine before it goes live
127.0.0.1 example.com
# Access a specific server within your network by it's hostname
192.168.1.100 fileserver
In these examples, we've created two entries in the /etc/hosts file:
- The first entry maps the hostname "example.com" to the local IP address "127.0.0.1". This allows you to test the website on your local machine before it goes live.
- The second entry maps the hostname "fileserver" to the IP address "192.168.1.100". This allows you to access the file server on your network using the hostname "fileserver" instead of the IP address "192.168.1.100".
It's important to note that the /etc/hosts file is used as a backup when a name server is not available. When you are connected to the internet, your computer will typically use a name server to resolve hostnames to IP addresses. However, if the name server is unavailable or if you are working offline, the /etc/hosts file will be used to resolve hostnames. This is why it's a good idea to keep the /etc/hosts file up to date and accurate.
In order for the changes you make to the /etc/hosts file to take effect, you will need to restart your network. On a Linux system, this can be done using the command /etc/rc.d/init.d/network restart
. This will reset the network interfaces and apply the changes you have made to the /etc/hosts file.