/etc/hosts
The /etc/hosts file is a system file in Unix-like operating systems that maps hostnames to IP addresses. It is used by the system to resolve hostnames to IP addresses before querying DNS servers. This file can be used for local hostname resolution and is particularly useful in network configurations and for troubleshooting.
Format of /etc/hosts
The /etc/hosts file consists of lines of text, each specifying an IP address followed by one or more hostnames. Comments can be added using the # character. Here is the general format:
<IP Address> <Hostname> [Alias...]Example of /etc/hosts
127.0.0.1 localhost
127.0.1.1 myhostname
192.168.1.1 router.local router
8.8.8.8 google-dnsIn this example:
127.0.0.1 localhostmaps the IP address127.0.0.1to the hostnamelocalhost.127.0.1.1 myhostnamemaps the IP address127.0.1.1to the hostnamemyhostname.192.168.1.1 router.local routermaps the IP address192.168.1.1to the hostnamesrouter.localandrouter.8.8.8.8 google-dnsmaps the IP address8.8.8.8to the hostnamegoogle-dns.
Editing /etc/hosts
Open the File: To edit the
/etc/hostsfile, you need superuser privileges. You can use a text editor such asnano,vim, orgedit. For example:sudo nano /etc/hostsModify the Entries: Add, remove, or modify entries as needed.
Save and Exit: Save your changes and exit the text editor.
Practical Uses
Local Development: Developers often use the
/etc/hostsfile to map development domain names tolocalhostor to specific IP addresses for testing purposes.127.0.0.1 myapp.localBlocking Unwanted Websites: By mapping unwanted websites to
127.0.0.1, users can effectively block access to these sites.127.0.0.1 unwantedwebsite.comHost Resolution in Small Networks: In small networks without a DNS server, the
/etc/hostsfile can be used to define hostname to IP address mappings for devices.192.168.1.100 server.local 192.168.1.101 printer.localOverriding DNS: If you need to temporarily override DNS resolution for a specific hostname, you can add an entry to
/etc/hosts.
Conclusion
The /etc/hosts file is a simple yet powerful tool for hostname resolution in Unix-like operating systems. It allows for local overrides of DNS queries, facilitating tasks such as development, troubleshooting, and network configuration. Understanding its format and usage can significantly enhance your ability to manage and configure network settings effectively.
Last updated