Question

How do you programmatically add a new entry to the Hosts file in Mac?

For example on Windows, you just open up a StreamWriter and output to the Hosts file. How do you do this on a Mac?

Was it helpful?

Solution

The hosts file is at

/etc/hosts

so you can add to it by just writing to it. But you should never delete the first few lines corresponding to the local host. Also, it's only accessible with the root privilege.

OTHER TIPS

  1. The simplest (free) way, would be to install the Hosts prefpane which would let you add or edit, enable or disable entries from System Preferences–without needing to navigate to the hosts file and swap it out manually. It keeps track of changes so that you can't delete those crucial first lines.

    http://www.macupdate.com/app/mac/40003/hosts

  2. If you are looking for a more "programmatic" way of accomplishing this, you could fork the developer's GitHub repo which contains the source code and Xcode project, and apply it towards your own project.

    https://github.com/specialunderwear/Hosts.prefpane

  3. There are other (paid) third-party apps that accomplish the same as the preference pane. I tried one called HostBuddy, but it was essentially the same as its free counterparts, with a few more features but confusing UI. There is a free trial though.

    https://clickontyler.com/hostbuddy/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top