TL;DR: The /etc/hosts
file in Unix-like systems maps hostnames to IP addresses for manual overrides or blocking websites. Using 0.0.0.0
for blocking is more efficient than 127.0.0.1
, as it leads to immediate connection failure without involving a round-trip to the local machine.
The /etc/hosts
file in Unix and Unix-like operating systems, like Linux and macOS, is used to map hostnames to IP addresses.
Prior to the widespread adoption of domain name systems (DNS), it was the primary method for mapping hostnames to their corresponding IP addresses. In modern usage, it often complements DNS, allowing for manual overrides, local domain definitions, or for blocking unwanted sites by redirecting them to addresses like 127.0.0.1
or 0.0.0.0
.
While both 127.0.0.1
and 0.0.0.0
achieves the same result (blocking the website), they have in fact specific uses:
127.0.0.1:
This is the loopback IP address, often represented as localhost
. It’s used to establish an IP connection to the same machine or host. Essentially, when you address 127.0.0.1
, you are referring to your own computer.
Commonly, it’s used for testing network services. If you run a local web server on your machine, accessing http://127.0.0.1
will connect to your local service.
In /etc/hosts
, it’s used to define the hostname for the local machine. This also here that the binding to localhost is made:
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
0.0.0.0:
/etc/hosts
, it’s used to block a destination. By mapping a domain to 0.0.0.0
, any request to that domain will fail, effectively blocking it. It’s a lightweight way to block unwanted network traffic.127.0.0.1
, which points back to your own machine, 0.0.0.0
is used to signify that there should be no response.Using 0.0.0.0
in your /etc/hosts
file for blocking unwanted domains can be faster compared to using 127.0.0.1
.
Indeed when you map a domain to 0.0.0.0
, it effectively tells your system that the address is invalid. This results in an immediate failure of any network requests to that domain, as the system recognizes that it’s an invalid address and rejects the connection immediately. There’s no attempt to establish a connection.
This bypasses the potential delay caused by the network stack trying to establish a connection to 127.0.0.1
. Indeed if there’s a server running on your machine that listens to the requested port, it will respond – typically with an error if the request doesn’t correspond to an actual service. This can take slightly longer because it involves a round-trip to your own machine and waiting for a response.
In practical terms, the speed difference is usually minimal, but 0.0.0.0
is slightly more efficient for blocking domains and a such this is what I use when I need it.