Saturday, May 26, 2012

How to edit the hosts file in Mac OS X

Many people have been asking me HOW TO edit your hosts file on a MAC.

This guide works on Leopard (10.5.x), Snow Leopard (10.6.x) & Lion (10.7.x)


How to edit the hosts file in Mac OS X – Leopard

Introduction

The hosts file is a text file that maps hostnames to IPaddresses.

Upon typing a url address on the browser, the system is checking if there is arelevant entry on the hosts file and gets the corresponding IP address, else itresolves the IP via the active connection’s DNS servers.

The hosts file can be edited to block certain hostnames(like ad-serving/malicious hosts), or used for web development purposes, i.e.to redirect domains to local addresses.

Editing the hosts file

Editing the hosts file in Mac OS X, is a prettyeasy task, especially if you are familiar with the terminal. Even if your not, just follow the following 5 steps and you'll be able to walk yourself through it with no problems.


Step 1 – Open the Terminal.app

Either by start typing Terminal on the Spotlight, or bygoing into Applications -> Utilities -> Terminal.



Step 2 – Open the hosts file

Open the hosts by typing on the Terminal that you have justopened:  
sudo nano /etc/hosts
Type your user password when prompted. 






Step 3 – Edit the hosts file

The hosts file contains some comments (lines starting withthe # symbol), as well as some default hostname mappings (e.g. 127.0.0.1 –localhost).
Simply append your new mappings underneath the default ones. Or edit one of thedefault values if you know what you are doing!
You can navigate the file using the arrow keys. The Mouse WILL NOT WORK inside the Terminal.app.

Here is the "stock" Hosts file

An Example:  If you wanted to block yahoo.com search engine, this is the value you would enter.
This will work for any Web Site / IP Address of your choosing.




Step 4 – Save the hosts file

When done editing the hosts file, press control-o to savethe file.
Press enter on the filename prompt, and control-x to exit the editor.

control-o to save the file
Press enter on the filename prompt

Step 5 – Flush the DNS cache

On Leopard you can issue a simple Terminal command to flushthe DNS cache, and have your host file changes to take immediate effect:  

sudo dscacheutil -flushcache
You can now test your new mappings on any browser.


Now that your all done, you can EXIT the Terminal.app



No comments:

Post a Comment