Toggle Hosts File Instantenously (content blocking)

PUBLISHED ON 27/09/2018 — PROJECTS

Intro

For a while now, I am using hosts file to block unwanted content at DNS resolve level.

The source for the blocked hosts file I am using can be obtained in the famous Steven Black github repository.

It works great, but sometimes, you just need that peice of internet that the list blocks.

Fear no more!

Implementation

The steps are written for macOS, but can be easily converted for any unix like operating system.

By adding two simple functions to your shellrc file, one can simply toggle the hosts file used.

The functions create a hardlink from /etc/hosts to a list you request to be used.

First we download the blacklist and save it as /etc/hosts-blocking:

$ cd /etc
$ wget https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts -O hosts-blocking

Next, we save the old hosts file to /etc/hosts-original:

$ sudo cp /etc/hosts /etc/hosts-original

Then just add this to your ~/.zshrc (should work for bash too):

function hosts-block {
    sudo ln -iv /etc/hosts-blocking /etc/hosts
    # Flush DNS cache
    sudo dscacheutil -flushcache;sudo killall -HUP mDNSResponder
}

function hosts-unblock {
    sudo ln -iv /etc/hosts-original /etc/hosts
    # Flush DNS cache
    sudo dscacheutil -flushcache;sudo killall -HUP mDNSResponder
}

Reload the .zshrc and you can use hosts-block and hosts-unblock to toggle.

If you are using any linux distribution, restart the nscd daemon after toggling the files. If you don’t have it, I highly recommend it.