Using The Hosts File

Published: {ts '2013-01-22 00:00:00'}
Author: Steven Neiland
Site Url: http://www.neiland.net/article/using-the-hosts-file/

Sometimes I forget that something that seems simple to me may not be for someone else. For example recently I was asked was there a way to tell an application running on a computer to look for a domain running on the same machine without having to go out to the internet.

For whatever reason my mind skipped straight over the obvious solution and went straight to reconfiguring the application and IIS. It was only the next morning as I was driving into work that I had the face->palm moment and realized that I had forgotten about the hosts file.

What Is The "Hosts" File

The hosts file is a simple text document which the operating system first checks to try resolve a domain name to an ip address. It is only after this file has been checked that the operating system goes out to look at domain name servers.

Modifying The Hosts File

As it is a simple text file all we need to do is open it with a simple text editor and add in our extra entries. Note some operating systems (windows) may require you to run the text editor with administrative access.

Windows

On windows the hosts file is located at:

C:\windows\systems32\drivers\etc\hosts

When trying to open this file on windows you may not be able to initially see it in the notepad file open dialogue as the hosts file does not have a file extension. Just set the file open window to show all file extensions.

Linux / Mac

On *nix based operating systems such as linux and mac the hosts file is (usually) located at:

/etc/hosts

Adding A Domain To Resolve To Localhost

As an example lets say we want to tell our computer to look for a domain "www.fakedomain.com" on our local machine. To do this open the hosts file and add a line entry for 127.0.0.1 (localhost) and the domain name.

#Resolve www.fakedomain.com to this computer 127.0.0.1 www.fakedomain.com #Also resolve fakedomain.com to this computer 127.0.0.1 fakedomain.com

What The Hosts File Cannot Do

I've seen this asked a few times so I figured it was worth a mention. The hosts file only resolves domain names to IP addresses. It cannot do anything about port numbers.