What is linux hosts file

Understanding /etc/hosts file in Linux

What Is /etc/hosts And Why Is It Used?

In order to send network traffic to a host, the numeric Internet Protocol (IP) address for that host must be known. The IP address is traditionally written as xxx.xxx.xxx.xxx where each xxx represents a value from 0 to 255, for an IPv4 network address. Computers require these addresses but humans find remembering numeric values difficult. The Domain Name Service (DNS) provides a mechanism to associate one or more alphanumeric names with a numeric IP address. On a Linux system, these readable names are converted to their numeric IP equivalents by the Resolver Library, contained in the libresolve.so files provided as part of the glibc RPM package. Programs that need to lookup the numeric IP address for a name issue calls to this library.

Host names and their IP addresses may be found in a variety of places: local files, remote DNS servers, or NIS+ servers, to name a few. The order these resources are searched depends on the hosts: entry in the /etc/nsswitch.conf file. This line typically looks like this:

This causes the resolver library to consult the local /etc/hosts file first; if the host name is not found there, then consult the remote DNS name servers identified by the /etc/resolv.conf file.

Linux does provide the bind RPM package to allow an administrative domain to configure and maintain its own DNS service, but frequently the size of the local network is only a few hosts and makes justifying the effort of maintaining a DNS service unwarranted.

Format of /etc/hosts File

The /etc/hosts file is an ordinary text file. Two types of lines are permitted:

  1. Empty Lines
  2. Host name definitions

Lines may be intermingled as needed. Comments begin with a hash symbol (#) and continue to the end of the line.

Associating Host Names And IP Addresses

For each host a single line should be present with the following information:

Fields of the entry are separated by any whitespace (spaces or tabs). The first field is the numeric IP address to be used for all the host names on this entry. Either an IPv4 address (10.1.2.3), an IPv6 address (2001:0db8:0000:0000:0000:0000:1428:57ab), or an IPv6 abbreviation (::1) may be used, depending on your requirements.

After the IP address, remaining tokens specify the locally-known hostnames associated with that IP address. By convention, the first name after the IP address is the canonical or fully-qualified domain name. An example of a canonical name would be server.example.com; this is the official name of the host.

Any remaining names defined for the IP address are aliases or alternate names for the official host name. For example, suppose that one of the duties assigned to server.example.com is to be the corporate FTP site. A suitable alias might then be myftp.example.com and this name could be added to the /etc/hosts entry after the canonical name. Many times, an alias is simply the host name, without any domain suffix. For example:

The advantage to listing the canonical host name as the first definition on the line is that IP-to-hostname conversion (similar to reverse DNS lookups) usually display only the first name found; convention uses the canonical name for this. In our example, the command:

Читайте также:  Windows 10 2004 проблемы smb

Note that we pinged myftp but results come from host myhost: this is a reliable hint that you are addressing an alias, not the actual host.

Источник

The Hosts File on Linux

All operating systems with network support have a hosts file to translate hostnames to IP addresses. Whenever you open a website by typing its hostname, your system will read through the hosts file to check for the corresponding IP and then open it. The hosts file is a simple text file located in the etc folder on Linux and Mac OS (/etc/hosts). Windows has a hosts file as well, on Windows you can find it in Windows\System32\drivers\etc\

Here is how it looks like:

From what we mentioned, you might be expecting this file to have a very long list of IPs and corresponding hostnames; but that is not true. The hosts file only contains several lines;

  • The first part, by default, contains the hostnames and IP addresses of your localhost and machine. This is the part you will usually modify to make the desired changes.
  • The second part has information about IPv6 capable hosts and you will hardly be editing these lines.

Whenever you type an address, your system will check the hosts file for its presence; if it is present there, you will be directed to the corresponding IP. If the hostname is not defined in the hosts file, your system will check the DNS server of your internet to look up for the corresponding IP and redirect you accordingly.

Why Edit /etc/hosts file?

By editing the hosts files, you can achieve the following things:

  • Block a website
  • Handle an attack or resolve a prank
  • Create an alias for locations on your local server
  • Override addresses that your DNS server provides
  • Control access to network traffic

How to Edit /etc/hosts file?

You can edit the hosts text file, located at /etc/hosts only as a superuser. You will first have to open it in text editors such as VI editor, Nano editor or gedit, etc. in the Linux terminal. You will then make the required changes and save the file for these changes to take effect.

In this article, we will use the Nano editor to edit the file. Please type the following command:

As mentioned before, we will be editing the first part of the hosts file where IP addresses and hostnames are defined. We will explain the following two ways in which you can make use of the hosts file: Advertisement

  • Block a website
  • Access Remote Computer Through an Alias

Block a Website

You can block a website by redirecting it to the IP of your localhost or the default route.

For example, if we want to block google.com, we can add the following text to our file:

Now when we open the google website, our system will take the IP of our localhost (127.0.0.1) from the hosts file and redirect us to that instead of the google IP from our DNS server.

Now when we open the google website, our system will take the IP of the default route (0.0.0.0) from the hosts file and redirect us to that instead of the google IP from our DNS server.

This is how the edited file will look like. Please save the changes by hitting ctrl+X.

Now when you try to open www.google.com from your browser, you will see an error message as follows:

Please note that we have defined the complete address www.google.com instead of just the hostname google.com in the hosts file because modern browsers sometimes circumvent the block if we only define the latter.

There are also some predefined blocklists available that you may use in your hosts file: https://github.com/StevenBlack/hosts

Читайте также:  Linux как пронумеровать страницы

Access Remote Computer through an Alias

Suppose we have a server located at a local network that we want to access. We usually have to type the server’s IP to access it unless it has been defined on our local DNS. One way to avoid typing the IP, again and again, is to assign an alias to the server in the hosts file as follows:

The IP corresponds to the location of the server we want to access and myserver is the new alias we want to use.

Now when we saved the file and type myserver in the address bar, we will be redirected to our remote server.

We have learned that by making very simple changes to the hosts file, we can customize and thus redirect the network traffic according to our needs. We can also get rid of a network attack or prank by restoring the hosts file to its default.

Karim Buzdar

About the Author: Karim Buzdar holds a degree in telecommunication engineering and holds several sysadmin certifications. As an IT engineer and technical author, he writes for various web sites. You can reach Karim on LinkedIn

Источник

Linux Hosts File Explained — Syntax and Uses

Linux hosts File – What Is This?

The purpose of the hosts file is simple – to map hostnames to IP addresses. Its function is the same as the function of the Domain Name System (DNS) but the difference is that unlike DNS, the hosts file is stored locally on the machine. This means that the administrator of the local machine can enter and edit the entries in the hosts file as required.

The hosts file is not unique to Linux. In fact, the hosts file is present in many operating systems, such as UNIX/Linux, the various Windows OS, Mac, Symbian, OS/2, etc. Actually, if an operating system can be used to access the Net, then most likely it has a hosts file. However, the location of the hosts file varies under different operating systems. Under Linux the typical location for the hosts file is in /etc/hosts but this is not an absolute rule for absolutely any Linux distro.

Syntax of the Linux hosts File

The syntax of the Linux hosts file isn’t sophisticated. The format for the hosts file is the same on Linux/UNIX and Windows and it is as follows:

[IP address] [domain name] [alias]

Therefore, if you want to add localhost, here is how the entry will look like:

It is important to note that /,\, and https:// are omitted. Otherwise, there is nothing special about the syntax of the entries in the Linux hosts file.

If you want to temporarily exclude some entries without deleting them forever, you can comment them out. The sign # is used for that.

The syntax of the Linux hosts file is pretty simple and for a small number of entries, you can use a conventional text editor. However, when you have many entries to input, then automated tools are what you need because they not only speed the process but also reduce the amount of errors.

Uses of the Linux hosts File

Linux hosts file isn’t an obsolete file, as it might look at first. Its basic uses are these:

  • To facilitate network testing. When you need to make a test server behave as if it were a real production server and to test how a particular applications or service performs, the hosts file is perfect for the purpose.
  • To accelerate browsing speed. When your browser doesn’t have to send DNS requests to a remote system, this speed browsing. However, have in mind that when the hosts file is large and/or it doesn’t contain a particular IP. This could seriously slowdown browsing speed.
  • To block adware and other pests. Finally, one more use of the Linux hosts file is to block adware and spyware. Fortunately, malware isn’t such a problem under Linux as it is under Windows but still there are tons of browser adware and spyware that are cross-platform, and because of this you can encounter them under Linux as well. When you add the IPs of such known adware and spyware networks to your hosts file, you won’t be seeing these nuisances.
Читайте также:  Microsoft windows most popular operating system

Источник

Файл hosts в Linux

Система доменных имен DNS используется для определения, какой IP принадлежит к нужному домену в сети интернет. Когда какой-либо программе понадобится обратиться к сайту по его доменному имени, операционная система отправляет к DNS-серверу запрос, чтобы узнать, по какому IP ей дальше передавать пакеты. Но так происходит не всегда. Например, когда мы обращаемся к домену localhost, то всегда запрос отправляется нашему локальному компьютеру.

Всему причиной файл hosts. Если вы раньше пользовались Windows, то, наверное, уже слышали о таком файле. Там чаще всего он использовался для того, чтобы быстро заблокировать доступ к какому-либо ресурсу. Но применение его гораздо шире. В этой статье мы рассмотрим, как настроить файл hosts в Linux, а также какие возможности он нам предоставляет.

Разрешение доменных имён в Linux

Прежде чем мы перейдём к самому файлу hosts, нужно разобраться, как происходит поиск IP-адреса для доменного имени в Linux. Я говорил, что операционная система сразу же отправляет запрос DNS-серверу, но это не совсем так. Существует определённый порядок поиска, согласно которому он выполняется. Этот порядок установлен в конфигурационном файле /etc/nsswitch.conf

Здесь нас интересует строчка hosts. В ней в порядке очередности записаны службы, которые используются для поиска IP-адреса для доменного имени. Пункт files означает использование файла /etc/hosts, а dns — сервиса доменных имён интернета. Если files расположена перед hosts, это означает, что сначала система попытается найти домен в /etc/hosts, а уже потом по DNS. По умолчанию дело обстоит именно так.

Настройка файла hosts в Linux

Нужный нам файл находится в директории /etc/. Для его открытия можно использовать любой текстовый редактор как в командной строке, так и в графическом интерфейсе, только открывать его нужно с правами суперпользователя. Например, с помощью vim:

sudo vi /etc/hosts

sudo gedit /etc/hosts

Синтаксис файла довольно простой. В нём находится несколько строчек с доменными именами и IP-адресами, которые нужно для них использовать. Каждая из них выглядит вот так:

ip_адрес домен алиас

Обычно первая же строчка создаёт правило для перенаправления всех запросов к домену localhost на локальный IP-адрес — 127.0.0.1:

Также в этом файле по умолчанию размещаются перенаправления для имени вашего компьютера и для IPv6-адресов. Вы можете создать свои настройки для любого нужного домена. Для этого нужно добавить строчку в конец файла. Например, направим все запросы к домену losst.ru на ip 127.0.0.1:

Обратите внимание, что здесь указывается только домен, без протокола. Префикс http или https указывать не нужно, иначе ничего работать не будет. А вот для поддомена www нужно создавать отдельную запись или записывать его в виде алиаса. Например:

127.0.0.1 losst.ru www.losst.ru

Теперь при запросе домена losst.ru будет открываться наш локальный IP. Чтобы вернуть доступ к оригинальному ресурсу, достаточно убрать добавленную строчку. Но вы можете использовать не только локальный адрес, но и любой другой. Это очень удобно, если вы только зарегистрировали домен и доменная зона ещё не успела обновиться, а вы уже хотите работать с новым сайтом. Просто добавьте данные в /etc/hosts и работайте как обычно.

Выводы

В этой небольшой статье мы разобрали, как выполняется настройка DNS через файл hosts Linux. Как видите, с его помощью вы можете блокировать доступ к нежелательным ресурсам, например, к которым программы не должны получить доступ, а также использовать его в работе веб-мастера.

Источник

Оцените статью