Skip to content

The Complete Guide to Hosts Files: Windows, Ubuntu, and macOS

When running raydium locally, it might be beneficial to use the host file to simulate the multiple domains for testing especially for multi-tenant setup.

The hosts file is a fundamental component of the hostname-to-IP-address resolution process on virtually all operating systems. Although modern networked environments rely heavily on DNS (Domain Name System), the hosts file provides a simple, static mechanism to override or supplement DNS lookups. This deep dive will explore the hosts file in detail, focusing on behavior, usage, and management on Windows, Ubuntu (representative of many Linux distributions), and macOS. Topics covered include history and purpose, file format and syntax, resolution order, operating-system–specific locations and editing procedures, advanced use cases (e.g., local development, site blocking), caching and flushing, security considerations, and troubleshooting.


Historical Context and Purpose

Origins

In the early days of ARPANET (precursor to the modern Internet), there was no global, hierarchical DNS. Instead, hostnames and their corresponding IP addresses were maintained in a single, centrally managed file called HOSTS.TXT (hosttable). The Network Information Center (NIC) at Stanford maintained and distributed HOSTS.TXT. Each connected site periodically downloaded the updated file to keep its local host table in sync.

Transition to DNS

As the network grew, maintaining a single HOSTS.TXT became untenable. In 1983, Paul Mockapetris introduced DNS: a distributed, hierarchical system for name resolution. DNS relieved the need for a centrally maintained hosts file for every machine. However, the concept of a local hosts file persisted. Today, each operating system retains a local hosts file (often in /etc/hosts), allowing administrators or users to override DNS entries on a per-machine basis.

Primary Purposes of a Hosts File

The hosts file serves several key purposes in modern computing environments. Static overrides allow you to redirect specific hostnames to chosen IP addresses, bypassing or supplementing DNS. Local development scenarios enable mapping of development or staging domains (e.g., dev.example.local) to local or private IPs, facilitating testing. Blocking and filtering capabilities let you redirect undesirable hostnames (e.g., ad servers, malicious domains) to 127.0.0.1 or another non-routable address to effectively block access. Finally, the hosts file provides a fallback mechanism that offers a final resolution check if DNS is unreachable or misconfigured.


Hosts File Format and Syntax

Regardless of platform, the hosts file follows a straightforward, column-based, line-oriented syntax. Each non-comment line maps an IP address to one or more hostnames. The general form is:

<IP_Address><separator><Hostname>[<separator><Alias1>][<separator><Alias2>]…[<separator># Comment]

The IP address can be IPv4 (e.g., 127.0.0.1) or IPv6 (e.g., ::1) and must be a valid, fully qualified IP. The separator consists of one or more tabs (\t) or spaces, with consistent use of at least one whitespace character required to distinguish columns. The hostname represents the canonical (primary) hostname for that IP, for example, example.com.

Aliases are optional additional names for the same IP, often used for short hostnames or subdomains. For example, mapping 127.0.0.1 to both localhost and mydev.local would look like:

127.0.0.1    localhost mydev.local

Comments are also optional and can take two forms: lines beginning with # are entirely comments, while inline comments follow a # after at least one whitespace separating them from the hostname or alias list:

192.168.0.10    internal-server  # Staging environment

Blank lines that are completely empty or contain only whitespace are ignored by the system.

Example (complete):

# Loopback IPv4
127.0.0.1    localhost

# Loopback IPv6
::1          localhost

# Custom mappings
127.0.0.1    dev.example.com dev
192.0.2.5    test.example.com  # Test env

Resolution Order and Integration with DNS

Each operating system employs a hostname resolution sequence (or lookup order) that dictates whether to check the hosts file before or after querying DNS. In broad terms, the system first checks the hosts file. If the requested hostname is found (and not commented out), it returns the corresponding IP. Otherwise, the system proceeds to the next step.

The system then resolves via DNS by performing a recursive or iterative DNS query based on system configuration (e.g., /etc/resolv.conf, DHCP-provided DNS servers). If DNS returns an answer, the system uses it. Finally, other methods may be consulted if configured, such as Name Service Switch (NSS) on Linux/Ubuntu for LDAP, NIS, or mDNS depending on /etc/nsswitch.conf. macOS employs the Directory Service framework, which may also consult Bonjour/mDNS, NetBIOS, or Active Directory if configured. Windows may consult NetBIOS or WINS if DNS lookup fails in certain network configurations.

Key Point: Because the hosts file is checked before DNS, it always takes precedence. This is why adding an entry for example.com to 127.0.0.1 will effectively "block" DNS resolution—Windows, Ubuntu, and Mac will never query DNS for that name so long as the hosts file entry exists and is active.


Operating System–Specific Details

Windows

File Location

The hosts file on Windows is located at C:\Windows\System32\drivers\etc\hosts. Note that C:\Windows\System32 is usually protected; therefore, standard users must have elevated privileges (Administrator) to modify this file.

Regarding file extension and attributes, the file has no extension (just hosts) and is typically marked as "Read-only" by default to prevent accidental changes. It is a plain ASCII text file, though Unicode or other encodings may cause unexpected behavior. Always use an ANSI/UTF-8 (without BOM) text editor.

Default Contents & Comments

Upon a default Windows installation, the hosts file often contains a template like:

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# Entries may be inserted below this line.
# Each entry should be kept on an individual line.
#
# The IP address should be placed in the first column followed by
# the corresponding hostname.
#
# For example:
#
#    102.54.94.97     rhino.acme.com     # source server
#     38.25.63.10     x.acme.com         # x client host

127.0.0.1       localhost
::1             localhost

The commented lines explain usage, while the active 127.0.0.1 and ::1 entries map the loopback addresses to localhost.

Editing the Hosts File on Windows

To edit the hosts file on Windows, you must first open Notepad or your preferred editor as Administrator. Press Start and type Notepad (or your preferred text editor). Right-click on the editor icon and select Run as administrator. Within Notepad, go to File → Open, then navigate to C:\Windows\System32\drivers\etc\. In the "File name" field, type hosts (be sure to select "All Files (.)" in the file type dropdown, since "Text Documents (*.txt)" won't show it). Click Open to load the hosts file.

When making changes, append new host-to-IP mappings below the existing loopback entries. Be sure to preserve or add line breaks as needed and maintain the format: <IP><tab or spaces><hostname> [aliases...] [# comment].

To save your changes, simply click Save. If you did not open as Administrator, you will receive an "Access is denied" or similar error. In that case, ensure you have elevated privileges.

After editing, changes may not be recognized immediately due to Windows' DNS caching service (DNS Client). To flush the cache, open a Command Prompt as Administrator (Start → type cmd → right-click → "Run as administrator") and run:

ipconfig /flushdns

You should see confirmation: Successfully flushed the DNS Resolver Cache. Now, your new hosts entries will be used on the next lookup.

Windows-Specific Behavior

Windows includes several specific behaviors worth noting. The Local DNS Cache (DNS Client Service) means Windows caches both positive (found) and negative (not found) lookups. Flushing via ipconfig /flushdns ensures that subsequent lookups re-read the hosts file.

For IPv6 entries, the default template shows ::1 localhost. If you wish to override IPv6 hostnames, map them similarly:

::1 someipv6test.local

Windows also has an optional lmhosts file (same folder, named lmhosts.sam as a sample) for legacy NetBIOS name resolution. This is distinct from hosts but can similarly map NetBIOS names to IPs. It is less common now and not used for DNS lookups. Unless you specifically need to map NetBIOS names, you can ignore lmhosts.

Regarding wildcard or subdomain mappings, the Windows hosts file does not implement wildcard matching. Each hostname must be explicitly listed. For example, to block all subdomains of example.com, you must individually map each subdomain:

127.0.0.1   www.example.com
127.0.0.1   api.example.com
127.0.0.1   blog.example.com

There is no shorthand like *.example.com in the Windows hosts file.

For encoding and BOM considerations, the hosts file must be saved without a Byte Order Mark (BOM). Notepad's default might add a BOM when saving as "UTF-8". Instead, choose "UTF-8 without BOM" (on newer Notepad versions, simply "UTF-8" does not include BOM). If in doubt, use a plain ANSI encoding. Using Unicode or UTF-16 can cause Windows to ignore the file or display garbled characters.


Ubuntu (Linux)

Ubuntu's handling of the hosts file is representative of many Linux distributions. The default resolver configuration often involves systemd-resolved or NetworkManager, but the hosts file remains a low-level override.

File Location

The hosts file is located at /etc/hosts. For file permissions and ownership, it is typically owned by root:root with permissions rw-r--r-- (0644). Regular users must use sudo (or have root privileges) to modify.

Default Contents

A default Ubuntu installation's /etc/hosts might look like:

127.0.0.1       localhost
127.0.1.1       ubuntu-machine-name

# The following lines are desirable for IPv6 capable hosts
::1             localhost ip6-localhost ip6-loopback
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters

The 127.0.1.1 ubuntu-machine-name entry is notable because Ubuntu uses this entry so that the machine's FQDN (fully qualified domain name) resolves to the local loopback when the system's primary interface is not up. Many Debian-based distros insert that line so that Java-based applications or services expecting the hostname to resolve don't fail.

Editing the Hosts File on Ubuntu

Before editing, it's wise to backup the original file:

bash
sudo cp /etc/hosts /etc/hosts.backup

You can edit with a text editor such as nano, vi, vim, or gedit (GUI). Using nano:

bash
sudo nano /etc/hosts

Using vi:

bash
sudo vi /etc/hosts

When modifying the file format and adding entries, place your overrides below the existing entries. For example:

192.168.50.100   dev.myapp.local
127.0.0.1        blocked.domain.com

Maintain whitespace separation. Tabs are common, but spaces are also acceptable so long as there is at least one whitespace delimiter.

To save and exit in nano, press Ctrl+O to write (save), then Enter, then Ctrl+X to exit. In vi/vim, press Esc, then type :wq and press Enter.

Flushing the DNS cache depends on what resolver is active in Ubuntu. There are several possibilities. If using systemd-resolved (Ubuntu 18.04 and later by default), restart or flush the cache with:

bash
sudo systemd-resolve --flush-caches

You can verify cache statistics:

bash
systemd-resolve --statistics

If using nscd (Name Service Cache Daemon), flush via:

bash
sudo /etc/init.d/nscd restart

or

bash
sudo service nscd restart

If using dnsmasq, restart via:

bash
sudo systemctl restart dnsmasq

If no caching daemon is in use, many Ubuntu setups do not run a dedicated DNS cache. In that case, edits to /etc/hosts take effect immediately on the next lookup without any explicit flush.

Linux-Specific Behavior

Name Service Switch (NSS) Order is controlled by /etc/nsswitch.conf which defines the lookup order. The relevant line is typically:

hosts:          files mdns4_minimal [NOTFOUND=return] dns mdns4

Here, files refers to /etc/hosts, mdns4_minimal is multicast DNS for IPv4 (commonly used for .local hostnames via Avahi), dns is standard DNS lookup, and mdns4 provides fallback for multicast DNS. Because files appears first, /etc/hosts always takes precedence over DNS. If you move or delete entries there, those names will be resolved via mDNS or DNS next.

For IPv6 considerations, an entry for ::1 localhost is usually present. If you wish to override IPv6 lookups, append:

::1   myipv6test.local

Regarding loopback vs secondary local entries, the line 127.0.1.1 ubuntu-machine-name is specific to Debian/Ubuntu, ensuring that the system's FQDN resolves locally even if the primary network interface is down. Do not remove that unless you understand the consequences (some services expect the local hostname to resolve).

For wildcard or subdomain mappings, the Linux hosts file does not support wildcard hostnames. You must list each hostname explicitly.


macOS

On macOS, the hosts file functions similarly to Linux/Ubuntu but integrates with Apple's Directory Services subsystem and mDNSResponder. Editing requires similar steps, and flushing the cache uses macOS-specific commands.

File Location

The hosts file is located at /etc/hosts. For file permissions and ownership, it is owned by root:wheel with permissions -rw-r--r-- (0644) and requires sudo to modify.

Default Contents

A stock macOS hosts file (newer versions) typically contains:

##
# 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
255.255.255.255 broadcasthost
::1             localhost

The comment block at the top provides guidance, and 255.255.255.255 broadcasthost defines the IPv4 "broadcast host."

Editing the Hosts File on macOS

First, backup the original:

bash
sudo cp /etc/hosts /etc/hosts.backup

You can open the file in a terminal-based or GUI text editor. For terminal-based with nano:

bash
sudo nano /etc/hosts

With vi:

bash
sudo vi /etc/hosts

For GUI-based editors like TextEdit or BBEdit, you can use:

bash
sudo open -a TextEdit /etc/hosts

This will ask for your password and open the file in TextEdit. However, some versions of TextEdit may not allow saving back to a root-owned path. If so, use Terminal-based editors.

When adding custom mappings, for example:

192.168.1.50    webdev.local
127.0.0.1       ads.example.com

Keep the existing localhost and broadcasthost entries intact.

To save and exit in nano, use Ctrl+O, Enter, then Ctrl+X. In vi/vim, use Esc, then :wq, Enter.

To flush the DNS cache, starting with macOS Yosemite (10.10) and later, the command is:

bash
sudo killall -HUP mDNSResponder

On macOS High Sierra (10.13) and Mojave (10.14), you may need:

bash
sudo killall -HUP mDNSResponder
sudo dscacheutil -flushcache

On macOS Catalina (10.15) and later, the single mDNSResponder flush is usually enough:

bash
sudo killall -HUP mDNSResponder

There is no feedback unless there is an error. After running, macOS will use the updated hosts file on subsequent lookups.

macOS-Specific Behavior

DNS caching is handled by mDNSResponder, which macOS uses to handle both DNS and Bonjour/mDNS lookups. Flushing the cache ensures the new entries are recognized. Unlike Linux, there is no persistent nscd or systemd-resolved by default (unless manually installed).

For name service order, macOS checks /etc/hosts first, then contacts DNS servers defined in System Preferences → Network → [Active Interface] → Advanced → DNS. If a cached answer exists in mDNSResponder's in-memory cache, /etc/hosts may not immediately be consulted until the cache is flushed.

Regarding IPv6 and IPv4, macOS includes both IPv4 (127.0.0.1 localhost) and IPv6 (::1 localhost) by default. Any additional IPv6 overrides must be explicitly added. If you wish to disable IPv6 lookups for a hostname, you can add an entry using ::0 or comment out the existing ::1 entry (not recommended), but be aware this may break local AAAA record resolution.

For wildcard mappings, as with other OSes, macOS does not support wildcard hostnames in the hosts file. Each desired mapping must be explicit.


Advanced Use Cases and Examples

Below are some common advanced scenarios and usage patterns for hosts files across Windows, Ubuntu, and macOS.

Local Development Environments

Use Case: You want to develop a website locally and have it respond to a realistic domain (e.g., project.local, shop.test) to mimic production.

First, choose a custom domain by picking a name ending in a non-public TLD, such as .local, .test, or .dev (be careful: Chrome now enforces HTTPS on .dev). For example, use myapp.local.

Next, add to the hosts file by mapping myapp.local to your local web server's IP (commonly 127.0.0.1 or your LAN IP if testing across devices). On Ubuntu/macOS:

127.0.0.1    myapp.local   # Local development

On Windows:

127.0.0.1    myapp.local   # Local development

Then configure your local web server. In Apache (Ubuntu/macOS), create a virtual host block in /etc/apache2/sites-available/myapp.local.conf:

<VirtualHost *:80>
    ServerName myapp.local
    DocumentRoot /var/www/myapp
    <Directory /var/www/myapp>
        AllowOverride All
        Require all granted
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/myapp.local-error.log
    CustomLog ${APACHE_LOG_DIR}/myapp.local-access.log combined
</VirtualHost>

Enable site and reload Apache:

bash
sudo a2ensite myapp.local.conf
sudo systemctl reload apache2

In Nginx (Ubuntu/macOS), create /etc/nginx/sites-available/myapp.local:

server {
    listen 80;
    server_name myapp.local;
    root /var/www/myapp;
    index index.html index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }
}

Enable and reload:

bash
sudo ln -s /etc/nginx/sites-available/myapp.local /etc/nginx/sites-enabled/
sudo systemctl reload nginx

On Windows (IIS or Apache), if using Apache XAMPP or WampServer, in httpd-vhosts.conf:

<VirtualHost *:80>
    ServerName myapp.local
    DocumentRoot "C:/xampp/htdocs/myapp"
    <Directory "C:/xampp/htdocs/myapp">
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Restart Apache service. In IIS, add a new site in IIS Manager, bind to port 80 with Host Name myapp.local, and ensure hosts file has 127.0.0.1 myapp.local.

Finally, test by navigating to http://myapp.local/ in your browser and confirm it resolves to your local codebase.


Blocking Unwanted Domains (Adware, Malicious Sites, Tracking)

Use Case: Prevent your machine from reaching certain domains (e.g., known ad servers, telemetry endpoints, malicious IPs) by redirecting them to a non-routable address.

Begin by selecting the redirect IP. Commonly use 127.0.0.1 (IPv4 loopback) or ::1 (IPv6 loopback). Some admins use 0.0.0.0 to minimize the wait time for resolution failures.

Add entries such as this example (Ubuntu/macOS/Windows):

127.0.0.1   ads.example.com    # Block ads.example.com
0.0.0.0     telemetry.tracker.io  # Block telemetry.tracker.io
::1         ipv6-blocked.local   # Block an IPv6-only resource

Lines beginning with # remain comments; ensure your actual redirects are not commented out.

The effect is that attempts to connect to those hostnames resolve to your local machine, causing the connection to fail. This provides a simple (but manual) form of content filtering.

For maintaining blocklists, some users download community-maintained blocklists (e.g., hosts files from someonewhocares.org, mvps.org, or GitHub repositories). Exercise caution as large lists can slow DNS resolution, so ensure you trust the source. On Ubuntu/macOS, you could append a curated blocklist to /etc/hosts, but be aware of performance impacts.

Regarding performance considerations, extremely large hosts files (tens of thousands of lines) can slow down lookups. Periodically review and prune unused entries.


Overriding DNS for Testing or Migration

Use Case: When migrating a site to a new IP, you can preview or test the new server by overriding the DNS for your local machine, without affecting other users.

First, identify the new server IP (e.g., 203.0.113.42). Then add a temporary hosts entry:

203.0.113.42    www.example.com    example.com

Now, requests from your machine to www.example.com and example.com go to 203.0.113.42, while everyone else still sees the old IP via DNS.

Test thoroughly by accessing the site in your browser, confirming functionality, and checking SSL validity (you may need to bypass certificate warnings if the SSL certificate is tied to the domain and not yet configured on the new server).

Finally, remove the hosts entry when done. Once you're satisfied and DNS is updated globally, remove or comment out that line and flush DNS cache to revert to normal DNS resolution.


IPv6–Specific Overrides

Use Case: Some local environments use IPv6; you might need to map hostnames to IPv6 addresses for testing or routing.

Add IPv6 entries like:

2001:db8:1:2::1234   workloadsrv.local

For examples, redirect to loopback for IPv6 (if you want to block an IPv6-only domain):

::1    ipv6ads.example.com

For dual-stack considerations, if both IPv4 and IPv6 addresses exist for the same hostname in the hosts file, most resolvers try IPv6 first (e.g., return the AAAA record before A record). You can place the IPv4 entry first or remove the IPv6 entry to force an IPv4 resolution. For example:

127.0.0.1       forceipv4.example.com
::1             forceipv4.example.com  # comment out to deprioritize IPv6

Aliases and Host Shortcuts

Use Case: Create short, memorable aliases for longer hostnames (e.g., dbdatabase.dev.local) to simplify command-line access.

For example:

192.168.1.200   database.dev.local db

The effect is that in your terminal, you can now ping db or connect via ssh user@db instead of typing ssh user@database.dev.local.

However, there are caveats to consider. Choose hostnames carefully to avoid conflicts with real, public hostnames or existing internal DNS. Always ensure there are no trailing spaces after your hostname entries, as some resolvers may treat trailing whitespace oddly.


Detailed OS-Specific Step-by-Step Guides

Below are step-by-step instructions, including subtle nuances, for editing and managing hosts files on Windows, Ubuntu, and macOS.

Windows: Step-by-Step

Open hosts as Administrator

To search for Notepad, press Windows Key or click the Start menu and type Notepad (or your chosen editor, e.g., Notepad++).

To run as Administrator, right-click on Notepad result and select Run as administrator. If prompted by UAC (User Account Control), click Yes.

To open the file, in Notepad, go to File → Open and navigate to C:\Windows\System32\drivers\etc\. In the "File name" box, type hosts (or select "All Files" from the file type dropdown to see hosts). Click Open.

Backup and Edit

For backup (optional but recommended), before editing, copy hosts to hosts.bak in the same folder. In File Explorer, right-click on hosts, select Copy, right-click in blank area, select Paste, then rename new file to hosts.bak.

To edit, scroll to the bottom of the file. After the existing entries, add new mappings. For example:

127.0.0.1    myproject.local    # Local development
0.0.0.0      ads.badsite.com    # Block badsite.com

Ensure there are no leading or trailing spaces in the IP address column. Use at least one tab or multiple spaces between IP and hostname.

To save, in Notepad, click File → Save. If editing with Notepad++ or another advanced editor, ensure you save with ANSI or UTF-8 (without BOM) encoding.

Tip: If you encounter "Access denied" or cannot save, you likely did not run as Administrator.

Flush DNS Cache

To open Command Prompt as Administrator, press Windows Key, type cmd, right-click Command Prompt, and select Run as administrator.

Run the flush command:

ipconfig /flushdns

The console should respond with confirmation:

Windows IP Configuration

Successfully flushed the DNS Resolver Cache.

To verify, test lookups by using ping or nslookup:

cmd
ping myproject.local

Confirm it resolves to 127.0.0.1.

Common Pitfalls and Tips (Windows)

Regarding file encoding, avoid saving as UTF-16 or adding a BOM. If the file is not plain ANSI/UTF-8, Windows may not parse it correctly.

For trailing spaces, avoid trailing spaces after IP or hostname. Some parsers may treat those as part of the hostname.

Concerning the read-only attribute, the file is sometimes marked "Read-only." After editing, ensure that attribute is removed if future edits are required. Right-click, select Properties, and uncheck Read-only.

Regarding antivirus or security software, some security suites monitor changes to the hosts file. If you see your edits reverted, check your security software's "Hostname protection" or "Anti-phishing" settings.


Ubuntu: Step-by-Step

Inspect /etc/hosts

To open Terminal, press Ctrl+Alt+T or search for "Terminal" in the application launcher.

View contents:

bash
cat /etc/hosts

Observe default entries mapping 127.0.0.1 and 127.0.1.1 to local hostnames and note any IPv6 lines beginning with ::1.

Backup and Edit

Backup:

bash
sudo cp /etc/hosts /etc/hosts.orig

Open in editor using nano (beginner-friendly):

bash
sudo nano /etc/hosts

Or using vi/vim:

bash
sudo vim /etc/hosts

To add or modify entries, scroll down and append new lines. For example:

192.168.56.10    testserver.local   # VM test server
127.0.0.1        oldsite.example.com  # Redirect oldsite to localhost

If you rename your machine's hostname, you can adjust the 127.0.1.1 line:

127.0.1.1    new-ubuntu-hostname

Standard header and IPv6 lines can remain unchanged unless you have a specific IPv6 override need.

To save changes, in nano use Ctrl+O, then Enter, then Ctrl+X. In vim, press Esc, then :wq, then Enter.

Flush DNS Cache (If Applicable)

To check for systemd-resolved, on Ubuntu 18.04+, systemd-resolved is often used:

bash
systemctl is-active systemd-resolved

If it returns active, flush with:

bash
sudo systemd-resolve --flush-caches

To check for nscd, if you installed nscd:

bash
dpkg -l | grep nscd

If present, flush via:

bash
sudo service nscd restart

To check for dnsmasq, if you are using dnsmasq for local DNS caching:

bash
systemctl is-active dnsmasq

If active, flush with:

bash
sudo systemctl restart dnsmasq

For no caching daemon, many desktop Ubuntu installations rely on direct file lookups. If no caching service is active, your changes take effect immediately.

Verify

Ping hostnames:

bash
ping testserver.local

Verify it resolves to 192.168.56.10.

Use getent:

bash
getent hosts testserver.local

This queries the Name Service Switch (NSS) and should return:

192.168.56.10   testserver.local

Common Pitfalls and Tips (Ubuntu)

For NSS configuration, check /etc/nsswitch.conf to see that the line for hosts begins with files:

hosts: files dns mdns4_minimal [NOTFOUND=return] mdns4

If files is missing or after dns, the hosts file may be bypassed.

Regarding IPv6 vs IPv4, if you create an IPv6 entry for a hostname and omit a corresponding IPv4 entry, some applications may prefer IPv6 by default. Ensure you include appropriate address families as needed.

For loopback vs local FQDN, do not remove or alter the default 127.0.1.1 ubuntu-machine-name entry unless you know the implications (e.g., certain scripts or services expect the hostname to resolve).

For file permissions, ensure the final file is owned by root:root with permissions 0644:

bash
sudo chmod 644 /etc/hosts
sudo chown root:root /etc/hosts

Beware of NetworkManager. Some network managers may overwrite or regenerate /etc/hosts entries for dynamically assigned hostnames. Generally, custom lines you add remain intact, but be mindful when changing hostnames via hostnamectl or GUI network tools.


macOS: Step-by-Step

Inspect /etc/hosts

To open Terminal, launch via Spotlight (Cmd+Space → type Terminal) or find it in Applications → Utilities.

View contents:

bash
cat /etc/hosts

Inspect default lines mapping 127.0.0.1 localhost, 255.255.255.255 broadcasthost, and ::1 localhost.

Backup and Edit

Backup:

bash
sudo cp /etc/hosts /etc/hosts.backup

Open in editor with nano:

bash
sudo nano /etc/hosts

Or with vi:

bash
sudo vi /etc/hosts

If you prefer a GUI, you can attempt:

bash
sudo open -a TextEdit /etc/hosts

Be aware that GUI editors sometimes struggle to save to system-protected paths. If saving fails via TextEdit, revert to Terminal-based.

To modify or add entries, append at the end:

10.0.1.50    internal-service.local   # Internal testing
127.0.0.1    block-this-ad.com        # Block ad

Preserve the existing default lines.

To save and exit, in nano use Ctrl+O, then Enter, then Ctrl+X. In vi use Esc, then :wq, then Enter.

Flush DNS Cache

For older macOS versions (Yosemite–El Capitan):

bash
sudo killall -HUP mDNSResponder

For High Sierra (10.13), Mojave (10.14):

bash
sudo killall -HUP mDNSResponder
sudo dscacheutil -flushcache

For Catalina (10.15) and later:

bash
sudo killall -HUP mDNSResponder

There is no confirmation message. If there is an error (e.g., "No matching processes belonging to you were found"), verify you typed the command correctly. This often indicates that mDNSResponder is not running under your user's privileges, but a simple retry with sudo usually works.

Verify

Ping hostnames:

bash
ping internal-service.local

Confirm it resolves to 10.0.1.50.

Use dscacheutil:

bash
dscacheutil -q host -a name internal-service.local

This queries the Directory Service cache directly. Expect output like:

name: internal-service.local
ip_address: 10.0.1.50

Common Pitfalls and Tips (macOS)

Regarding mDNSResponder vs Discoveryd, on older macOS versions (10.10.4–10.10.10), Apple briefly used discoveryd instead of mDNSResponder. To flush the cache on those versions, run:

bash
sudo discoveryutil mdnsflushcache
sudo discoveryutil udnsflushcaches

Newer versions have reverted to mDNSResponder. If you're uncertain which daemon is running, check:

bash
ps aux | grep -E 'mDNSResponder|discoveryd'

For System Integrity Protection (SIP), modern macOS (10.11+) includes SIP, preventing modification of protected locations unless SIP is disabled. However, /etc/hosts is not protected by SIP; it resides outside the sealed system volume. Editing it with sudo is sufficient.

Regarding network locations and multiple network interfaces, if you switch between different network interfaces (e.g., Ethernet vs. Wi-Fi), DNS resolution may behave differently or have separate caches. Flushing mDNSResponder covers all.

For macOS Catalina's drive separation, Catalina introduced a read-only system volume. Since /etc/hosts resides on the data volume, you can modify it normally without disabling read-only protection.


Troubleshooting and Common Issues

Hosts File Ignored or Not Working

If the hosts file is being ignored or not working, several issues could be the cause. Incorrect file encoding occurs when the file is saved with a BOM or using UTF-16/UTF-32, causing the resolver to skip it. Always use plain ASCII or UTF-8 without BOM.

Syntax errors include missing whitespace between IP and hostname, accidentally removing the leading # from comment lines that you didn't intend to activate, or using a non-standard delimiter (e.g., a comma instead of space/tab).

A misplaced file on Windows means ensuring it's in C:\Windows\System32\drivers\etc\hosts and not in C:\Windows\SysWOW64\drivers\etc\hosts (64-bit systems may have a copy in both). Always edit the one in System32\drivers\etc.

Caching issues involve forgetting to run ipconfig /flushdns on Windows, not flushing systemd-resolved, nscd, or dnsmasq on Ubuntu, or not signaling mDNSResponder properly on macOS.

Order of resolution changes can occur on Linux if /etc/nsswitch.conf is modified and the hosts: line does not include files first, causing /etc/hosts to be bypassed. For example, if it reads hosts: dns files, DNS is tried before files. Always ensure files appears first for the hosts file to take priority.

Overlapping or conflicting tools can cause issues. On Ubuntu, if you run a local caching service (e.g., dnsmasq), it may override or bypass direct /etc/hosts entries if misconfigured. Ensure the caching service respects the hosts file. On Windows, some antivirus or security suites actively monitor and revert unauthorized changes to the hosts file. Check your security application's settings if edits keep reverting.

Missing administrative privileges means failure to launch editor as Administrator (Windows) or use sudo (Ubuntu/macOS) will prevent you from saving changes.


Duplicate or Conflicting Entries

Multiple entries for the same host can cause confusion. If you have two lines mapping example.com to different IPs, the resolver typically honors the first entry it encounters. For clarity, avoid duplicates or comment out the one you do not want.

Hosts file vs. DNS entries means if a hostname exists in both hosts and DNS, the hosts file takes precedence. However, some applications may cache the DNS result earlier; flush caches and restart applications if necessary.

NetBIOS or WINS configuration (Windows) refers to legacy NetBIOS name resolution (via lmhosts) that can conflict with hosts. Be aware that mapping a NetBIOS name in lmhosts may override hosts for certain legacy tools.


Security and Best Practices

Only add trustworthy entries by including only mappings for domains you trust or explicitly want to override. Avoid copying large, unverified blocklists that may inadvertently redirect legitimate domains or malware domains you don't intend to block.

Restrict write access on shared machines or servers by limiting hosts file edits to administrators. On Linux/macOS, keep permissions at 0644 and ownership root:root. On Windows, enforce file permissions so that only Administrators can write.

Monitor for unauthorized changes because hosts file hijacking is a common technique for malware (redirecting bank domains to phishing servers). Use file integrity monitoring (FIM) solutions to watch for unexpected changes. On Windows, consider third-party tools or built-in auditing to alert if hosts is modified.

Avoid overly broad overrides by not mapping entire TLDs or using wildcard entries (not supported anyway); explicitly map only the exact hostnames you intend. Wildcard needs are better handled via DNS server configuration, not hosts files.

Backup before batch edits. If you import a large block of entries (e.g., downloaded blocklist), make a copy of the existing file so you can revert if issues arise.

Be cautious with IPv6 and IPv4 dual-mapping in mixed environments. Ensure you do not inadvertently break IPv6 connectivity by overriding ::1 or removing existing entries. If you block a site via both IPv4 and IPv6, remember to add both 0.0.0.0 example.com and ::1 example.com (or appropriate IPv6 blocking address).

Document customizations when working as part of a team by maintaining a comment block in the hosts file explaining each non-default entry's purpose. This aids future troubleshooting. For example:

# Local development for Project X
127.0.0.1   projectx.local   # Dev environment

# Blocking telemetry for App Y
0.0.0.0     telemetry.appy.com  # Block App Y telemetry

Tools and Automation

Scripted Edits

For Linux/macOS, use shell scripts to append or remove lines. Example (append if not already present):

bash
HOST_ENTRY="127.0.0.1 mynewdomain.local"
if ! grep -Fxq "$HOST_ENTRY" /etc/hosts; then
    sudo sh -c "echo \"$HOST_ENTRY\" >> /etc/hosts"
fi

For Windows (PowerShell), append a new line if not present:

powershell
$entry = "127.0.0.1`tmynewdomain.local"
$hostsPath = "$env:WinDir\System32\drivers\etc\hosts"
$exists = Select-String -Path $hostsPath -Pattern "mynewdomain\.local"
if (-not $exists) {
    Add-Content -Path $hostsPath -Value $entry -Encoding ASCII
}

Configuration Management (CM) Tools

Ansible:

yaml
- name: Ensure hosts file contains custom mappings
  hosts: all
  become: yes
  lineinfile:
    path: /etc/hosts
    line: "192.168.33.10 ansible-test.local"
    state: present

Chef:

ruby
hostsfile_entry '192.168.33.10' do
  hostname  'chef-test.local'
  action    :create
  comment   'Created by Chef'
end

Puppet:

puppet
host { 'puppet-test.local':
  ensure       => present,
  ip           => '192.168.33.10',
  host_aliases => ['ptl'],
}

These ensure environments remain consistent and idempotent.

Version Control

On servers where multiple administrators collaborate, consider storing the hosts file in a Git repository (or other VCS) as plain text. Use deployment scripts to push updates to /etc/hosts or the Windows equivalent. Always coordinate changes to avoid conflicts.


Troubleshooting Scenarios

Below are some concrete troubleshooting questions and solutions related to hosts file usage.

Scenario 1: "My new hosts entry isn't taking effect—DNS still resolves to the public IP."

First, verify the entry by opening the hosts file and confirming that your line is not commented out (no leading #) and checking for typos in the IP or hostname.

Ensure proper whitespace by making sure there is at least one tab or several spaces between IP and hostname. An example of a problematic line would be:

127.0.0.1mytest.local  # No whitespace

Should be:

127.0.0.1   mytest.local  # Correct

Flush cache on Windows with ipconfig /flushdns, on Ubuntu (with systemd-resolved) with sudo systemd-resolve --flush-caches, and on macOS with sudo killall -HUP mDNSResponder.

Check NSS configuration (Linux) by ensuring /etc/nsswitch.conf has files before dns in the hosts: line:

hosts: files dns mdns4

Restart relevant services. On Windows, restart the DNS Client service. You can restart it via Services.msc or net stop dnscache && net start dnscache. On Ubuntu, possibly restart NetworkManager or systemd-resolved if you use them. On macOS, restart mDNSResponder.

Consider application-level caching, as some applications maintain their own DNS cache (e.g., browsers). Close and reopen the application or, for browsers, restart or navigate to chrome://net-internals/#dns and clear the host cache.

Scenario 2: "I accidentally overwrote my hosts file—how can I restore default entries?"

For Windows, use the backup you hopefully created (hosts.bak) and copy it back to hosts. If no backup exists, create a new file with the minimal default content:

text
# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost
127.0.0.1       localhost
::1             localhost

For Ubuntu, restore from /etc/hosts.orig if you made a backup:

bash
sudo cp /etc/hosts.orig /etc/hosts

Otherwise, recreate default entries:

127.0.0.1       localhost
127.0.1.1       ubuntu-machine-name

# The following lines are desirable for IPv6 capable hosts
::1             localhost ip6-localhost ip6-loopback
ff02::1         ip6-allnodes
ff02::2         ip6-allrouters

For macOS, if you have a backup /etc/hosts.backup, restore it:

bash
sudo cp /etc/hosts.backup /etc/hosts

Otherwise, recreate the default file:

##
# 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
255.255.255.255 broadcasthost
::1             localhost

After restoration on all OSes, flush DNS cache as previously described.

Scenario 3: "My web application isn't reachable via the alias I set in the hosts file, but I can ping it successfully."

Check web server configuration to ensure that your web server (Apache/Nginx/IIS) has a virtual host configured for that hostname. Pinging only tests network-level resolution, not application-level routing. For example, if you mapped dev.local to 127.0.0.1, ensure Apache has a <VirtualHost *:80> block with ServerName dev.local.

Clear browser cache, as modern browsers aggressively cache DNS. Clear browser caches or test in "Private/Incognito" mode. For Chrome, navigate to chrome://net-internals/#dns and press Clear host cache.

Consider SSL/TLS considerations. If your site uses HTTPS, your certificate must include the hostname. If you attempt https://dev.local with a certificate for example.com, you will receive a certificate mismatch or untrusted certificate error.

Check application-level host binding, as some frameworks (e.g., Laravel's APP_URL, Node.js servers) explicitly bind to certain hostnames. Ensure your application's configuration recognizes the alias and listens on 0.0.0.0 (all interfaces) or 127.0.0.1, not solely localhost.


Security Implications

Potential for malware and hosts hijacking exists because malware often modifies hosts entries to redirect legitimate domains (e.g., banking sites) to malicious IPs. Monitoring and restricting write access is crucial.

Disabling unwanted telemetry is possible when some administrators deliberately block telemetry or update servers (e.g., Microsoft's, Apple's) by mapping their hostnames to loopback. Exercise caution: this can break legitimate update or authentication mechanisms.

For temporary vs permanent changes, use comments (#) to temporarily disable an entry instead of deleting it. Example:

#127.0.0.1   oldtest.local   # Temporarily disabled for local dev

Version control and audit trails are important for critical servers. Store /etc/hosts or C:\Windows\System32\drivers\etc\hosts in a version-controlled repository (e.g., Git) with strict access controls. This ensures you can audit changes and revert if needed.

DNS rebinding protections should be considered because advanced attackers utilize DNS rebinding to bypass hosts file restrictions. Although the hosts file mitigates straightforward DNS resolution, be aware that some browsers enforce additional protections to neutralize rebinding attacks.


Summary of Best Practices

Always back up the original hosts file before editing to enable easy rollback in case of errors or unintended consequences. Run editor with elevated privileges (Administrator or sudo) to ensure you can save changes without permission errors. Use plain ASCII or UTF-8 without BOM when saving to prevent encoding issues that cause the resolver to ignore the file. Maintain at least one whitespace delimiter (tab or spaces) between IP and hostname to guarantee correct parsing.

Do not include wildcard entries—list each hostname explicitly because hosts files do not support wildcard; explicit entries avoid confusion. Flush DNS cache after editing to ensure immediate effect so that system and applications use the updated mappings. Monitor file integrity using file integrity monitoring or version control to guard against unauthorized or malicious modifications. Comment liberally to document the purpose of each non-default entry to aid in future troubleshooting by clarifying why each override exists.

Avoid excessively large blocklists—be selective and trust sources because extremely large hosts files can slow lookup performance and may contain outdated or incorrect entries. Verify application-level configuration (e.g., web server virtual hosts, SSL certificates) to ensure hostname resolution via hosts file aligns with application bindings and prevents "site not found" despite correct network resolution.


Conclusion

The hosts file remains a powerful, straightforward mechanism for controlling hostname resolution at the operating system level. By editing this plain-text file, administrators and users can override DNS to point hostnames to specific IP addresses (commonly for local development), redirect unwanted or malicious domains to loopback addresses (for blocking or privacy), and temporarily preview migrations or bypass DNS for troubleshooting.

While modern OSes have introduced caching layers (systemd-resolved on Ubuntu, mDNSResponder on macOS, and the DNS Client service on Windows), the fundamental behavior of the hosts file persists: it is always checked before DNS. Understanding the exact file path, syntax conventions, permission requirements, and cache-flushing procedures is critical for each platform.

On Windows, the file is located at C:\Windows\System32\drivers\etc\hosts; edit in Administrator-mode Notepad and run ipconfig /flushdns after changes. On Ubuntu (Linux), use /etc/hosts with sudo nano or sudo vim and flush via systemd-resolve --flush-caches or restart caching daemons if present. On macOS, edit /etc/hosts using sudo nano or sudo vi (or TextEdit with care) and flush via sudo killall -HUP mDNSResponder.

By adhering to best practices—backing up, monitoring integrity, and documenting entries—one can leverage the hosts file safely and effectively across Windows, Ubuntu, and macOS environments. Whether you are a developer setting up a local test environment, a system administrator enforcing access restrictions, or simply a user managing personal privacy, mastering the hosts file is an essential skill in your networking toolbox.