Hosts on OSX

If you’ve done web development on a local machine and had to juggle multiple applications, you probably wound up assigning independent URLs to each application via the hosts file. And if you’ve jumped between platforms, you may have stumbled for a moment trying to figure out where to add your new records. OSX is no different.

OSX’s host file, located at /etc/hosts contains entries listing IP followed by assigned name.

127.0.0.1 localhost

It’s pretty simple and seems like it should work fine. This isn’t always the case. In earlier revisions, the hosts file was only read when networking booted. Despite this being fixed, I still run into the occasional finickiness when making changes. Luckily, OSX had NetInfo manager to handle situations like this. Unluckily, it’s been removed in Snow Leopard. Luckily again, dscl and its cohort have been added in its place, complete with manpages.

To create, read, or delete entries with one line, you can use the following commands, respectively.

sudo dscl localhost -create /Local/Default/Hosts/www.example.local IPAddress 127.0.0.1

dscl localhost -read /Local/Default/Hosts/www.example.local IPAddress 127.0.0.1

sudo dscl localhost -delete /Local/Default/Hosts/www.example.local IPAddress 127.0.0.1

[sudo] dscl, on its own, opens up an interactive session that treats the directory services tree like a directory, navigable with cd and ls. You can modify entries as above, but using the create, read, and delete commands directly. In addition, you can see (though not change) the existing /etc/hosts lines under /BSD/local. dscacheutil -configuration will show you the order of precedence.

Finally, you may need to run dscacheutil -flushcache immediately afterwards to see your changes take effect.

12/30/10 at 11:41pm
1 note | View comments
  1. dennyabraham posted this