Что такое the host windows

В этой статье мы расскажем, что такое файл hosts и где он лежит.

hosts — это текстовый документ, в котором прописаны соответствия доменов IP-адресам. Когда вы вводите домен в адресной строке браузера, в первую очередь запрос IP-адреса отправляется к файлу hosts. Если в нем не прописана информация об искомом сайте, запрос перенаправляется к системе DNS.

Как выглядит файл hosts в Windows:

Как выглядит файл hosts в Linux:

Как появился файл hosts

В 1970-х годах появилась прародительница современного интернета: сеть под названием ARPAnet. Она состояла из нескольких сотен порталов с информацией. За маршрутизацию в этой сети отвечал файл hosts.txt: в нем хранились соответствия между именем ресурса и его IP-адресом.

В то время за hosts.txt отвечал Сетевой информационный центр Стэнфордского исследовательского института (сокращенно NIC SRI). Если в сети появился новый сайт, администраторы отправляли информацию об изменениях в NIC SRI. После этого они синхронизировали свой файл hosts с данными из NIC. Это происходило 1-2 раза в неделю.

Однако по мере распространения интернета эта схема работы стала невозможна: объем информации рос, и синхронизировать данные стало значительно сложнее.

В 1984 году появились документы, в которых была описана система DNS. Именно она пришла на замену hosts.txt.

Файл hosts по-прежнему существует, но его назначение изменилось. Он есть на каждом компьютере и отвечает за отображение сайтов на конкретном устройстве. На глобальную паутину hosts не влияет.

Как можно использовать файл hosts

Файл hosts можно использовать для проверки работы сайта: это полезно, если вы недавно зарегистрировали новый домен или изменили DNS-серверы для существующего. Обновление DNS происходит в течение 24 часов, однако hosts позволяет увидеть сайт раньше. Для этого в нем нужно прописать доменное имя и IP-адрес хоста.

Что такое хост? Это сервер или услуга, на которой размещен ваш сайт. Уточнить ее IP-адрес можно у поставщика услуг.

Где находится файл hosts

Расположение файла hosts зависит от семейства и версии ОС, которая установлена на вашем компьютере.

  • Путь к файлу hosts на Windows 10: c:\windows\system32\drivers\etc\hosts
  • Путь к файлу hosts на Windows 11: c:\windows\system32\drivers\etc\hosts
  • Путь к файлу hosts на Windows 7: c:\windows\system32\drivers\etc\hosts
  • Путь к файлу hosts на Linux: /etc/hosts
  • Путь к файлу hosts на macOS: /private/etc/hosts

Не удается изменить файл hosts: как это исправить

Иногда попытка изменить hosts завершается ошибкой. С этим можно столкнуться, если вы редактируете файл в системе Windows.

Чтобы решить эту проблему, откройте Блокнот от имени администратора. Для этого:

  1. Кликните по строке поиска. Нажмите на Блокнот правой кнопкой мыши и выберите Запуск от имени администратора:

  2. Нажмите на меню Файл и выберите Открыть.

  3. Выберите файл hosts на вашем компьютере и нажмите Открыть.
  4. Добавьте данные о вашем сайте. В примере:
    123.123.123.123 — IP-адрес вашего хостинга,
    sweb.ru — доменное имя вашего сайта.
  5. Затем нажмите Файл и выберите Сохранить

Что такое localhost

localhost — это домен, который позволяет обратиться к вашему компьютеру напрямую. Это имя привязано к IP-адресу 127.0.0.1.

Как правило, localhost используется для настройки сетевых инструментов: например, если вы настроили сервер на компьютере и хотите к нему обратиться по имени или IP.

Помимо этого, localhost можно использовать, чтобы закрыть доступ к какому-либо сайту. Предположим, вы хотите заблокировать vk.com на конкретном компьютере. Тогда в файл hosts необходимо добавить строку:

127.0.0.1 vk.com

Как восстановить оригинальный файл hosts

Если вы случайно удалили файл hosts, его можно восстановить вручную. Для этого перейдите в папку, в которой он должен храниться. Затем создайте текстовый файл без расширения, назовите его hosts. После этого файл необходимо наполнить. Содержимое по умолчанию зависит от ОС, которая установлена на вашем компьютере.

Стандартный hosts для Windows:


# Copyright (c) 1993-2006 Microsoft Corp.

#

# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
# 102.54.94.97 rhino.acme.com # source server
# 38.25.63.10 x.acme.com
# x client host
# localhost name resolution is handle within DNS itself.
# 127.0.0.1 localhost
# ::1 localhost

Стандартный hosts для Linux:


127.0.0.1 localhost

127.0.1.1 username

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

Вместо username укажите имя вашей учетной записи на компьютере.

Стандартный hosts для MacOS:


##

# 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

После этого сохраните файл.

Несмотря на то, что файл hosts уже не влияет на работу сайтов в глобальной сети, он помогает решить некоторые важные задачи на вашем компьютере.

Applies ToWindows 8 Windows 8.1 Windows 7 Windows Vista Windows XP Windows 10 Windows 11

Аннотация

Рекомендации, приведенные в этой статье, позволяют вернуть содержимое файла hosts к используемому по умолчанию.

Что такое файл Hosts

Файл Hosts используется операционной системой для сопоставления удобных для человека имен узлов с числовыми IP-адресами, которые идентифицируют и находят узел в IP-сети. Файл hosts является одним из нескольких системных ресурсов, которые адресуют сетевые узлы в компьютерной сети и являются общей частью реализации IP-адресов операционной системы.

Файл Hosts содержит строки текста, состоящие из IP-адреса в первом текстовом поле, за которым следует одно или несколько имен узлов. Каждое поле отделено пробелом (по историческим причинам часто предпочтение отдают знакам табуляции, но пробелы также используются). Файл также может включать строки с примечаниями, обозначенные символом #, который ставится в начале каждой такой строки. Пустые строки в файле игнорируются.

Если файл Hosts изменен по умолчанию, сброс его может помочь устранить некоторые проблемы с подключением.

Решение

Чтобы восстановить параметры файла Hosts по умолчанию, выполните указанные ниже действия в зависимости от используемой версии операционной системы.

Чтобы восстановить параметры файла hosts по умолчанию, выполните указанные ниже действия.

1. Откройте Блокнот. Для этого найдите «Блокнот», а затем коснитесь или щелкните значок Блокнот .

2. Скопируйте следующий текст и вставьте его в файл:

  • # Copyright (c) 1993-2006 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a ‘#’ symbol. # # For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handle within DNS itself. # 127.0.0.1 localhost # ::1 localhost

3. В меню Файл выберите Сохранить как, введите hosts в поле Имя файла (как показано на следующем рисунке), а затем сохраните файл на рабочем столе.

Снимок экрана: сохранение файла hosts

4. Закройте Блокнот.

5. Выполните поиск по запросу %WinDir%\System32\Drivers\Etc, а затем щелкните значок папки «Файл «.

6. Коснитесь и удерживайте файл Hosts или щелкните его правой кнопкой мыши, выберите команду Переименовать, а затем переименуйте файл в Hosts.old.

7. Скопируйте или переместите файл Hosts, созданный на шаге 3, с рабочего стола в папку %WinDir%\System32\Drivers\Etc . Если вам будет предложено ввести пароль администратора, нажмите кнопку Продолжить.

Чтобы восстановить параметры файла hosts по умолчанию, выполните указанные ниже действия.

1. Откройте Блокнот. Для этого найдите «Блокнот» с помощью Кортаны, а затем коснитесь или щелкните значок Блокнот .

2. Скопируйте следующий текст и вставьте его в файл:

  • # Copyright (c) 1993-2006 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a ‘#’ symbol. # # For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handle within DNS itself. # 127.0.0.1 localhost # ::1 localhost

3. В меню Файл выберите Сохранить как, введите hosts в поле Имя файла (как показано на следующем рисунке), а затем сохраните файл на рабочем столе.

Снимок экрана: сохранение файла hosts

4. Закройте Блокнот.

5. Выполните поиск по запросу %WinDir%\System32\Drivers\Etc с помощью Кортаны, а затем щелкните значок папки «Файл «.

6. Коснитесь и удерживайте файл Hosts или щелкните его правой кнопкой мыши, выберите команду Переименовать, а затем переименуйте файл в Hosts.old.

7. Скопируйте или переместите файл Hosts, созданный на шаге 3, с рабочего стола в папку %WinDir%\System32\Drivers\Etc . Если вам будет предложено ввести пароль администратора, нажмите кнопку Продолжить.

Чтобы восстановить параметры файла hosts по умолчанию, выполните указанные ниже действия.

1. Откройте Блокнот. Для этого проведите пальцем от правого края экрана, коснитесь пункта Поиск, введите Блокнот, а затем коснитесь значка Блокнота . Если вы используете мышь, наведите указатель мыши на правый верхний угол экрана, переместите указатель мыши вниз, нажмите кнопку Поиск, введите Блокнот, а затем — Блокнот.

2. Скопируйте следующий текст и вставьте его в файл:

  • # Copyright (c) 1993-2006 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a ‘#’ symbol. # # For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handle within DNS itself. # 127.0.0.1 localhost # ::1 localhost

3. В меню Файл выберите Сохранить как, введите hosts в поле Имя файла (как показано на следующем рисунке), а затем сохраните файл на рабочем столе.

4. Закройте Блокнот.

5. Откройте папку %WinDir%\System32\Drivers\Etc. Для этого выполните следующие действия:

  • а.  Проведите пальцем от правого края экрана, коснитесь пункта Поиск, введите выполнить, а затем коснитесь значка Выполнить . Или, если вы используете мышь, наведите указатель на правый верхний угол экрана, переместите указатель мыши вниз, выберите Поиск, введите выполнить, а затем щелкните значок Выполнить .

  • б.  В поле Открыть введите команду %WinDir%\System32\Drivers\Etc и нажмите кнопку ОК.

6. Выберите файл Hosts, выберите Переименовать, а затем переименуйте файл в Hosts.old.

7. Скопируйте или переместите файл Hosts, созданный на шаге 3, в папку %WinDir%\System32\Drivers\Etc. Если вам будет предложено ввести пароль администратора, нажмите кнопку Продолжить.

Чтобы самостоятельно восстановить параметры файла hosts до значений по умолчанию, сделайте следующее:

  1. Нажмите кнопку Пуск, нажмите кнопку Выполнить, введите Notepadи нажмите кнопку ОК.

  2. Найдите свою версию Windows из приведенного ниже списка и скопируйте следующий текст для этой версии Windows, а затем вставьте его в Блокнот:

  • Для Windows 7:

  • # Copyright (c) 1993-2006 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a ‘#’ symbol. # # For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handle within DNS itself. # 127.0.0.1 localhost # ::1 localhost
  • Для Windows Vista или Windows Server 2008:

  • # Copyright (c) 1993-2006 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a ‘#’ symbol. # # 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
  • Для Windows XP или Windows Server 2003:

  • # Copyright (c) 1993-1999 Microsoft Corp. # # This is a sample HOSTS file used by Microsoft TCP/IP for Windows. # # This file contains the mappings of IP addresses to host names. Each # entry should be kept on an individual line. The IP address should # be placed in the first column followed by the corresponding host name. # The IP address and the host name should be separated by at least one # space. # # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a ‘#’ symbol. # # 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

3. В меню Файл выберите Сохранить как, введите hosts в поле Имя файла , а затем сохраните файл на рабочем столе.

В меню Файл выберите команду Сохранить как, введите "hosts" в поле Имя файла, а затем сохраните файл на рабочий стол.

4. Выберите Пуск > Выполнить, введите %WinDir%\System32\Drivers\Etc, а затем нажмите кнопку ОК.

5. Выберите файл Hosts и переименуйте его в Hosts.old.

6. Скопируйте или переместите файл Hosts, созданный на шаге 3, в папку %WinDir%\System32\Drivers\Etc. Если вам будет предложено ввести пароль администратора, нажмите кнопку Продолжить.

Дополнительная информация

Поддержка Windows XP прекращена

Корпорация Майкрософт прекратила поддержку Windows XP 8 апреля 2014 г. Это могло повлиять на безопасность и своевременную установку обновлений для вашего программного обеспечения. Узнайте, что это значит для вас и как оставаться защищенным.

Поддержка Windows Server 2003 прекращена 14 июля 2015 г.

Корпорация Майкрософт прекратила поддержку Windows Server 2003 14 июля 2015 г. Это могло повлиять на безопасность и своевременную установку обновлений для вашего программного обеспечения. Узнайте, что это значит для вас и как оставаться защищенным.

Нужна дополнительная помощь?

Нужны дополнительные параметры?

Изучите преимущества подписки, просмотрите учебные курсы, узнайте, как защитить свое устройство и т. д.

The computer file hosts is an operating system file that maps hostnames to IP addresses. It is a plain text file. Originally a file named HOSTS.TXT was manually maintained and made available via file sharing by Stanford Research Institute for the ARPANET membership, containing the hostnames and address of hosts as contributed for inclusion by member organizations. The Domain Name System, first described in 1983 and implemented in 1984,[1] automated the publication process and provided instantaneous and dynamic hostname resolution in the rapidly growing network. In modern operating systems, the hosts file remains an alternative name resolution mechanism, configurable often as part of facilities such as the Name Service Switch as either the primary method or as a fallback method.

The hosts file is one of several system facilities that assists in addressing network nodes in a computer network. It is a common part of an operating system’s Internet Protocol (IP) implementation, and serves the function of translating human-friendly hostnames into numeric protocol addresses, called IP addresses, that identify and locate a host in an IP network.

In some operating systems, the contents of the hosts file is used preferentially to other name resolution methods, such as the Domain Name System (DNS), but many systems implement name service switches, e.g., nsswitch.conf for Linux and Unix, to provide customization. Unlike remote DNS resolvers, the hosts file is under the direct control of the local computer’s administrator.[2]

The hosts file contains lines of text consisting of an IP address in the first text field followed by one or more host names.[3] The host names map to the IPs, not vice versa. Each field is separated by white space – tabs are often preferred for historical reasons, but spaces are also used. Comment lines may be included; they are indicated by an octothorpe (#) in the first position of such lines. Entirely blank lines in the file are ignored.[4] For example, a typical hosts file may contain the following:

127.0.0.1  localhost loopback
::1        localhost

This example only contains entries for the loopback addresses of the system and their host names, a typical default content of the hosts file. The example illustrates that an IP address may have multiple host names (localhost and loopback), and that a host name may be mapped to both IPv4 and IPv6 IP addresses, as shown on the first and second lines respectively.

Location in the file system


edit

The location of the hosts file in the file system hierarchy varies by operating system. It is usually named hosts, without an extension.

Operating System Version(s) Location
Unix, Unix-like, POSIX /etc/hosts[5]
Microsoft Windows 3.1 %WinDir%\HOSTS
95, 98, ME %WinDir%\hosts[6]
NT, 2000, XP,[7] 2003, Vista,
2008, 7, 2012, 8, 10, 11
%SystemRoot%\System32\drivers\etc\hosts[8]
Windows Mobile, Windows Phone Registry key under HKEY_LOCAL_MACHINE\Comm\Tcpip\Hosts
Apple Macintosh 9 and earlier Preferences or System folder
Mac OS X 10.0–10.1.5[9] (Added through NetInfo or niload)
Mac OS X 10.2 and newer /etc/hosts (a symbolic link to /private/etc/hosts)[9]
Novell NetWare SYS:etc\hosts
OS/2, eComStation, ArcaOS «bootdrive»:\mptn\etc\
Symbian Symbian OS 6.1–9.0 C:\system\data\hosts
Symbian OS 9.1+ C:\private\10000882\hosts
MorphOS NetStack ENVARC:sys/net/hosts
AmigaOS < 4 AmiTCP:db/hosts
4 DEVS:Internet/hosts
AROS ENVARC:AROSTCP/db/hosts
Android /etc/hosts (a symbolic link to /system/etc/hosts)
iOS iOS 2.0 and newer /etc/hosts (a symbolic link to /private/etc/hosts)
TOPS-20 SYSTEM:HOSTS.TXT
Plan 9 /lib/ndb/hosts
BeOS /boot/beos/etc/hosts[10]
Haiku /system/settings/network/hosts[11]
OpenVMS UCX UCX$HOST
TCPware TCPIP$HOST
RISC OS 3.7, 5 !Boot.Resources.!Internet.files.Hosts
later boot sequence !Boot.Choices.Hardware.Disabled.Internet.Files.Hosts[12]

The ARPANET, the predecessor of the Internet, had no distributed host name database. Each network node maintained its own map of the network nodes as needed and assigned them names that were memorable to the users of the system. There was no method for ensuring that all references to a given node in a network were using the same name, nor was there a way to read the hosts file of another computer to automatically obtain a copy.

The small size of the ARPANET kept the administrative overhead small to maintain an accurate hosts file. Network nodes typically had one address and could have many names. As local area TCP/IP computer networks gained popularity, however, the maintenance of hosts files became a larger burden on system administrators as networks and network nodes were being added to the system with increasing frequency.

Standardization efforts, such as the format specification of the file HOSTS.TXT in RFC 952, and distribution protocols, e.g., the hostname server described in RFC 953, helped with these problems, but the centralized and monolithic nature of hosts files eventually necessitated the creation of the distributed Domain Name System (DNS).

On some old systems a file named networks is present that is similar to a hosts file, containing names of networks.[13]

Extended applications


edit

In its function of resolving host names, the hosts file may be used to define any hostname or domain name for use in the local system.

Redirecting local domains
Some web service and intranet developers and administrators define locally defined domains in a LAN for various purposes, such as accessing the company’s internal resources or to test local websites in development.[14]
Internet resource blocking
Entries in the hosts file may be used to block online advertising, or the domains of known malicious resources and servers that contain spyware, adware, and other malware. This may be achieved by adding entries for those sites to redirect requests to another address that does not exist or to a harmless destination such as the local machine.[15] Commercial software applications may be used to populate the hosts file with entries of known undesirable Internet resources automatically. In addition, user-created hosts files which block nuisance servers are publicly available.[16][17]
Fravia described these files variously as «scrolls», «precious», and «powerful» in his anti-advertisement pages, where this usage of hosts was first published.[17]
Software piracy
Some pirated versions of software rely on a modified hosts file to prevent software from contacting the activation servers of the publisher, although activation servers sometimes appear in general purpose hosts files.[18]

The hosts file may present an attack vector for malicious software. The file may be modified, for example, by adware, computer viruses, or trojan horse software to redirect traffic from the intended destination to sites hosting malicious or unwanted content.[19] The widespread computer worm Mydoom.B blocked users from visiting sites about computer security and antivirus software and also affected access from the compromised computer to the Microsoft Windows Update website.

In some cases, malware has modified the library responsible for loading the hosts file in order to redirect it to a file it is able to control freely.[20]

  • DNSBL, a DNS-based blackhole list
  • Content-control software
  • Ad filtering
  1. ^ Internet Systems Consortium. «The Most Widely Used Name Server Software: BIND». History of BIND. Retrieved 2017-07-01.
  2. ^ Cisco Networking Academy Program: First-Year Companion Guide (2nd ed.). Cisco Systems. 2002. p. 676. ISBN 1-58713-025-4.
  3. ^ Penetration Testing: A Survival Guide. Packt Publishing Ltd. 18 January 2017. ISBN 978-1-78728-988-8.
  4. ^ «Hosts(5) — Linux manual page».
  5. ^ «Linux Network Administrators Guide: Writing hosts and networks files». Retrieved May 16, 2010.
  6. ^ «Hosts File». Archived from the original on July 20, 2011. Retrieved August 10, 2011.
  7. ^ «Microsoft KB Q314053: TCP/IP and NBT configuration parameters for Windows XP». Retrieved August 28, 2010.
  8. ^ «Microsoft KB 972034 Revision 2.0: default hosts files». Retrieved August 28, 2010.
  9. ^ a b «Mac OS X: How to Add Hosts to Local Hosts File». Retrieved August 28, 2010.
  10. ^ «The Haiku/BeOS Tip Server». Archived from the original on January 28, 2013. Retrieved November 30, 2012.
  11. ^ «Haiku UserGuide:Network». Retrieved January 17, 2019.
  12. ^ RISC OS 6.14
  13. ^ «Writing hosts and networks Files». tldp.org. Retrieved 2021-03-02.
  14. ^ «Building / Testing via the Hosts File». Ohio State University Web Hosting. OCIO. 9 October 2015. Retrieved 5 August 2018.
  15. ^ Gordon; -Tx. «Gordon and -Tx explanations about the use of Gordon’s hosts file». Web Searchlores. +Fravia. Archived from the original on 26 December 2018. Retrieved 5 August 2018.
  16. ^ Hofstetter, Constantin. «/etc/hosts to block shock sites etc». GitHub. Retrieved 5 August 2018.
  17. ^ a b Vianello, Francesco «Fravia». «Antiadvertisement Lab». Web Searchlores. +Fravia. Archived from the original on 15 May 2009. Retrieved 5 August 2018.
  18. ^ «yhosts». GitHub. Retrieved 21 June 2021.
  19. ^ «Remove Trojan.Qhosts». Symantec. Archived from the original on October 21, 2007. Retrieved May 16, 2010.
  20. ^ Arntz, Pieter (21 September 2016). «Hosts file hijacks». Malwarebytes Labs. Retrieved 5 August 2018.
  • Windows
    • Beginners Guide on Editing Hosts File
    • Microsoft TCP/IP Host Name Resolution Order
    • List of Microsoft domains that Windows won’t redirect with a host file
  • Mac
    • How to block unwanted domains with a HOSTS file on Mac OS X 10.2 or later
  • Linux
    • How to block unwanted advertisements with /etc/hosts file on Linux

Understanding the Host File: The Backbone of Network Communication

In the realm of computing and networking, the concept of a «Host File» plays an essential role that often goes unnoticed by the average user. While the term may not evoke the same level of recognition as more prominent components of technology, such as the operating system or web browser, the Host File is a critical element that enables seamless communication across networks. This article dives into the intricacies of Host Files, exploring their function, configuration, common use cases, and their evolution in the context of modern networking.

What is a Host File?

A Host File is a simple text file used by operating systems to map hostnames to IP addresses. It serves as a local DNS (Domain Name System) resolver, translating human-friendly domain names into machine-readable IP addresses. When a user attempts to access a website, the system first consults the Host File before querying a DNS server. This mechanism allows for quick resolution of hostnames, especially on local networks or in environments where DNS may not be readily accessible.

Historical Background

The origins of Host Files date back to the early days of the internet when the number of computers was limited, and a centralized method of translation was not yet established. The very first Host File, known as «hosts.txt,» was created in 1983 by the Stanford Research Institute. This file contained a list of hostnames and their associated IP addresses, serving as the foundation for future DNS functionalities.

As the number of computers and websites grew exponentially, the limitations of static Host Files became apparent. Managing an ever-growing list of addresses was impractical, leading to the creation and expansion of the DNS system in the late 1980s. Despite this evolution, Host Files remain relevant today due to their ease of use and functionality in managing small networks and local environments.

Structure of the Host File

The Host File is structured in a straightforward format. Each entry typically consists of an IP address followed by one or more hostnames. Here is an example entry:

192.168.1.10    example.local

Key Elements

  1. IP Address: This is the numerical label assigned to each device connected to a network. It can be either an IPv4 or IPv6 address.
  2. Hostname: A human-readable name that corresponds to the IP address. This can be an FQDN (Fully Qualified Domain Name) such as www.example.com or a simple local hostname like example.local.
  3. Comments: The Host File also allows for commenting. Any line that begins with a # is considered a comment and is ignored by the system. This is useful for adding explanations or notes for future reference.

Location of the Host File

The location of the Host File varies by operating system:

  • Windows: C:WindowsSystem32driversetchosts
  • Linux/Unix: /etc/hosts
  • macOS: /etc/hosts

It’s vital to have administrative or root permissions to edit the Host File, as changes can affect network resolution.

Working with the Host File

Editing the Host File is a common practice for network administrators and developers. The ability to manually map hostnames to IP addresses allows for flexibility in testing, development, and network management.

Basic Operations

  1. Viewing the Host File:

    • On Windows, open Command Prompt and use notepad C:WindowsSystem32driversetchosts.
    • On Linux or macOS, use nano /etc/hosts or vim /etc/hosts in the terminal.
  2. Editing the Host File:

    • Open the Host File in a text editor.
    • Add or modify entries by following the format discussed above.
    • Save the file and close the editor.
  3. Flushing the DNS Cache: After modifying the Host File, it may be necessary to flush the DNS cache to ensure changes are recognized.

    • In Windows, use the command: ipconfig /flushdns.
    • In Linux, the command may vary by distribution, but often it’s: sudo systemd-resolve --flush-caches.

Example Use Cases

  1. Local Development: Developers often use the Host File to point a domain name to a local server (e.g., on localhost). This allows for testing using a URL that resembles the final production URL.

    127.0.0.1    mylocalapp.local
  2. Network Diagnostics: Administrators can use the Host File to troubleshoot issues by redirecting traffic to different IP addresses. For example, if a website is down, they can redirect users to a backup server.

  3. Blocking Unwanted Sites: By redirecting unwanted domains to 127.0.0.1 (localhost), users can effectively block access to ads or malicious websites.

    127.0.0.1    example-ad.com
  4. Testing in a Controlled Environment: In scenarios where multiple versions of the same service are running (like multiple web servers), the Host File allows the selection of which service to access without requiring DNS changes.

Limitations of the Host File

While the Host File provides numerous benefits in specific scenarios, it does come with its drawbacks:

  1. Scalability: The Host File is not designed for handling large-scale environments. As the number of entries increases, it can become unwieldy and challenging to manage.

  2. Static Nature: Changes to the Host File require manual editing and may not reflect real-time updates. This can lead to outdated mappings if regular maintenance is not performed.

  3. Single Point of Failure: If the Host File becomes corrupt or accidentally deleted, hostname resolution for the mapped entries will fail, potentially disrupting network operations.

The Role of DNS in Modern Networking

The emergence of DNS was primarily a solution to the limitations of the Host File. DNS allows for distributed management of hostname resolution and can dynamically update and propagate changes across the internet.

How DNS Works

DNS functions by creating a hierarchical structure of names that correspond to IP addresses. When a user inputs a URL into a web browser, the browser sends a request to the DNS resolver, which processes the request and retrieves the corresponding IP address from its cache or queries other DNS servers if the information is not cached.

Advantages of DNS Over Host File

  1. Automation: DNS provides automated management of address resolution, with the ability to add, remove, or modify entries easily without manual file edits.

  2. Scalability and Distribution: DNS is designed to handle billions of entries, making it suitable for large organizations and global websites.

  3. Redundancy and Reliability: With multiple DNS servers distributed across networks, DNS offers improved reliability and redundancy. If one server fails, others can take over to ensure continued service.

The Future of Host Files

As technology continues to evolve, the role of the Host File remains relevant, especially in specific use cases. With the rise of cloud computing, virtualization, and containerization, the Host File has adapted to fulfill practical purposes in modern architectures.

Integration with Cloud Services

In cloud environments, the Host File can be used to facilitate communication between microservices or virtual machines. By manually defining the mappings, developers can manage service interactions without relying solely on external DNS.

Development and Testing Environments

The simplicity and immediacy of changes made through the Host File continue to make it a valuable tool for developers working in controlled environments or during the testing phases of application development.

Security Considerations

While the Host File serves important functions, it also introduces potential security risks. An attacker with access to the Host File can manipulate hostname resolutions, redirecting users to phishing sites or malicious servers.

Best Practices to Enhance Security

  1. Restrict Access: Limit permissions to edit the Host File to trusted users only.
  2. Regular Audits: Periodically review the Host File for unauthorized entries or modifications.
  3. Use of Security Software: Employ firewalls and antivirus solutions to monitor for suspicious activities that could indicate tampering with the Host File.

Conclusion

The Host File remains a vital, yet often overlooked, component of networking and system administration. With a history rooted in the early development of computer networking, it continues to provide practical benefits in various contexts, particularly in local development, network diagnostics, and access control.

While modern DNS has largely supplanted the Host File for managing large-scale networks, the file’s simplicity, speed, and direct control make it indispensable in specific situations. As technology evolves, so too will the applications and relevance of the Host File, ensuring its place in the toolkit of network professionals for years to come.

In summary, understanding and leveraging the capabilities of the Host File can enhance network management, optimize development processes, and fortify security practices. Recognizing its historical significance and current applications will empower users to effectively utilize this foundational element in the ever-complex landscape of networking.

The Hosts file, a.k.a etc/hosts has been around since 1984. Every operating system has one, including Windows. You may have encountered the term etc/hosts without knowing what it means, and why it is used. If you are a web developer, you surely know what this file is, and you want to find it quickly. In this guide, we explain what the Hosts file is, where it is located in Windows, what a host entry is, and how to edit the Hosts file without stumbling into permission errors. Let’s get started:

What is the Hosts file in Windows?

The Hosts file (also referred to as etc/hosts) is a text file used by Windows (and other operating systems) to map IP addresses to host names or domain names. This file acts as a local DNS service, for your local computer, and it overrides the mappings from the DNS server that your computer is connected to, through the network.

The etc/hosts file in Windows

The etc/hosts file in Windows

Where is the Hosts file located in Windows?

The Hosts files (or etc/hosts) is found in the following folder: «C:\Windows\System32\drivers\etc»

The location of the Hosts file, in Windows

The location of the Hosts file, in Windows

It is a file with no file extension, that can be opened and viewed in any text editor, including Notepad.

What is host entry in Windows?

The Hosts file stores host entries. They are standardized lines of text that use the following format: IPaddress Hostname Comment. The first part is the IP address to redirect to, the second part is the domain that you want to redirect, and the third is a comment. The comment is not mandatory only the first two parts are. You can separate the three components of a host entry with spaces or TABs (press the TAB key once or twice). For example, you can add a line that says: «127.0.0.1 www.google.com»

Editing the Hosts file in Notepad

Editing the Hosts file in Notepad

Once you save the entry above, Windows redirects the domain www.google.com to your local computer, in all your apps and web browsers.

What is 127.0.0.1?

127.0.0.1 is a special purpose IP address that leads to the localhost, which is your computer. It is also called «loopback address,» meaning an address that leads back to the computer using the address. Unlike standard IP addresses, the loopback address is not associated with any hardware, and it is not physically connected to a network. This address is used by apps and services that are installed on your computer, to communicate with the localhost, meaning your computer.

localhost redirect

localhost redirect

Your computer also has a unique IP address, different from 127.0.0.1, associated with your network card, that is used to communicate with other devices and services over the network or the internet.

Most often, the localhost IP address is used when installing a web server on your computer, for web development, so that the web pages that are created can be run locally, and tested in a web browser, as if they were live on the internet.

To avoid conflicts in computer networks, the IP addresses used for network devices can be anything except 127.0.0.1. For example, if you manually try to modify the IP address of your network card, in Windows, you receive an error stating that: «IP addresses starting with 127 are not valid because they are reserved for loopback address. Please specify some other valid value between 1 and 223.»

IP addresses starting with 127 are not valid

IP addresses starting with 127 are not valid

How to open and view the Hosts (etc/hosts) file in Windows

You can edit the Hosts file using any text editor. Let’s use Notepad, for example. First, and most important, is that you open Notepad (or your favorite text editor) with administrator permissions. One way to do that is to search for the word «notepad» in Windows 10, right-click (or tap and hold) the Notepad search result, and then click or tap «Run as administrator.» In the UAC prompt that is shown, press Yes.

Open Notepad as admin

Open Notepad as admin

Now you need to open the Hosts file. Click or tap File and then Open, or press CTRL+O on your keyboard.

Open a file in Notepad

Open a file in Notepad

Browse to «C:\Windows\System32\drivers\etc» or copy and paste the path in the address field of the Open window, and press Enter.

Open C:WindowsSystem32driversetchosts in Notepad

Open C:\Windows\System32\drivers\etc\hosts in Notepad

At first, «no items match your search» meaning that you do not see any files. That’s because the Hosts file does not have a file extension, and Notepad is looking only for files with the «.txt» extension. Click or tap the drop-down list to the right of the File name field, and choose «All Files (*.*).»

See All Files with Notepad

See All Files with Notepad

Now you see all the files in the folder, including hosts. Select the file and press Open.

Open C:WindowsSystem32driversetchosts in Notepad

Open C:\Windows\System32\drivers\etc\hosts in Notepad

How to edit the Hosts (etc/hosts) file in Windows

After you have opened the Hosts file, you can edit it, and add, change or remove entries, as you do in any other text file.

Remember that all the entries that you add must use this format: IP address Hostname. Add a line like «127.0.0.1 www.google.com» or «192.168.1.1 www.webapp.com»

Editing the Hosts file in Notepad

Editing the Hosts file in Notepad

When you are done editing the Hosts file, you need to save your changes. If changes are made and not saved, notice that the tile of the Notepad window starts with a * sign. To save your changes, go to File and then Save or press CTRL+S on your keyboard.

Saving the Hosts file in Notepad

Saving the Hosts file in Notepad

After you have saved your changes, they are applied immediately and override the mappings from the DNS server that your computer is connected to.

Why do people use the Hosts file?

Most casual computer users are not going to use the Hosts file unless they want to pull a prank on someone and use it to block their access to Google, Facebook or some other site, and make them think that it is down, and no longer working. The people using the Hosts file most frequently are web developers who create websites and web apps, which must be tested locally, before publishing them on the internet.

Google.com blocked by the Hosts file

Google.com blocked by the Hosts file

IT professionals also use the Hosts file to block access to specific sites and web resources, on the computers they are managing at work. For example, they can use it to block advertising in their business network, from specific ad networks.

Malware can also use the Hosts file to redirect your web traffic to remotely controlled servers and steal personal information or other data.

I can’t edit the Hosts file in Windows! What do I do?

When editing and saving the Hosts file in Windows, you may receive an error message that states: «You don’t have permissions to save to this location.» This happens because you did not open Notepad or the text editor that you are using, with administrator permissions. Read the sections above and see how to start Notepad with administrator permissions.

Error message: You don't have permissions to save in this location

Error message: You don’t have permissions to save in this location

After you do that, you can edit the Hosts file without any errors and permission problems.

How do you use the Hosts file in Windows?

Thank you for reading this tutorial. We hope that we have managed to answer all your questions about the Hosts file. Before closing, tell us in a comment, how you plan to use the Hosts file in Windows? Is it for work or just prank on a friend or family member? Comment below and let’s share our experiences working with the Hosts file.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Драйвера для intel hd graphics 4400 windows 7 x64
  • Rust desk server установка windows
  • Windows 10 применить path без перезагрузки
  • Запуск игр на эмуляторе windows
  • Автозагрузка в windows 10 где находится как убрать или добавить программы