Где находится файл hosts и как его отредактировать
Изменить файл hosts в windows не так уж и сложно, причин его изменения может быть несколько, например вы хотите добавить туда IP адреса какого либо из своих новых сайтов что бы он открывался до того как обновятся DNS, или наоборот запретить определенным сайтам открываться.
Файл 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 вам нужно сделать следующее:
Перейти по адресу: C:\Windows\System32\drivers\etc после чего в папке ETC вы увидите искомый файл HOSTS.
Для того что бы изменить (отредактировать) файл hosts нужно кликнуть по нему правой кнопкой мыши и выбрать Открыть после чего вы убидите это меню:
В списке программ вам нужно выбрать Блокнот и нажать Ок, после чего файл hosts откроется как обычный текстовый документ, чем он по сути и является. После внесения правок вам останется его стандартно сохранить, как будто вы отредактировали документ .txt.
На это все, теперь вы знаете как быстро отредактировать файл hosts.
Подписывайте на канал , задавайте по данной теме любые вопросы и я вам обязательно помогу. Так же можете внести предложение по теме ‘Создание и настройка сайтов, уроки по Windows’ и следующая статья будет об этом.
gethostname function (winsock.h)
The gethostname function retrieves the standard host name for the local computer.
Syntax
Parameters
A pointer to a buffer that receives the local host name.
The length, in bytes, of the buffer pointed to by the name parameter.
Return value
If no error occurs, gethostname returns zero. Otherwise, it returns SOCKET_ERROR and a specific error code can be retrieved by calling WSAGetLastError.
Error code | Meaning |
---|---|
WSAEFAULT | The name parameter is a NULL pointer or is not a valid part of the user address space. This error is also returned if the buffer size specified by namelen parameter is too small to hold the complete host name. |
WSANOTINITIALISED | A successful WSAStartup call must occur before using this function. |
WSAENETDOWN | The network subsystem has failed. |
WSAEINPROGRESS | A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function. |
Remarks
The gethostname function returns the name of the local host into the buffer specified by the name parameter. The host name is returned as a null-terminated string. The form of the host name is dependent on the Windows Sockets provider—it can be a simple host name, or it can be a fully qualified domain name. However, it is guaranteed that the name returned will be successfully parsed by gethostbyname and WSAAsyncGetHostByName.
The maximum length of the name returned in the buffer pointed to by the name parameter is dependent on the namespace provider.
If the gethostname function is used on a cluster resource on Windows ServerВ 2008, Windows ServerВ 2003, or WindowsВ 2000 Server and the CLUSTER_NETWORK_NAME environment variable is defined, then the value in this environment variable overrides the actual hostname and is returned. On a cluster resource, the CLUSTER_NETWORK_NAME environment variable contains the name of the cluster.
The gethostname function queries namespace providers to determine the local host name using the SVCID_HOSTNAME GUID defined in the Svgguid.h header file. If no namespace provider responds, then the gethostname function returns the NetBIOS name of the local computer.
The maximum length, in bytes, of the string returned in the buffer pointed to by the name parameter is dependent on the namespace provider, but this string must be 256 bytes or less. So if a buffer of 256 bytes is passed in the name parameter and the namelen parameter is set to 256, the buffer size will always be adequate.
WindowsВ PhoneВ 8: This function is supported for Windows Phone Store apps on WindowsВ PhoneВ 8 and later.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.
hosts — файл трансляции доменных имен в сетевые адреса узлов — IP-адреса
Файл host — имена узлов в IP-адреса
OS Windows — файл hosts
В файле hosts содержатся строки записей, которые состоят из IP-адреса, и одного или нескольких имен узлов. То есть в нём происходит перевод понятных для пользователей имен узлов в числовые адреса (IP-адреса)
После символа # размещены комментарии
Запись:
145.255.14.187 google.com, позволяет перейти на сайт поисковой системы Google, без обращения к системе доменных имён — DNS.
Первоначально преобразование доменных имен в IP-адреса производилось только с использованием hosts, который составлялся и рассылался на каждую из машин в локальной сети.
Файл hosts OS Windows находится в каталоге — C:\Windows\System32\drivers\etc\
IP — Internet Protocol (ай-пи. протокол Internet ) — В сети Internet для физического обмена данными (на аппаратном уровне), управления передачей данных, процессами в сети и маршрутизации потоков данных, используется протокол IP.
hosts — текстовый файл, содержащий базу данных доменных имен и используемый при их трансляции в сетевые адреса узлов. Запрос к этому файлу имеет приоритет перед обращением к DNS-серверам.
DNS (Domain Name System — система доменных имён) — используется для получения IP-адреса соответствующее имени хоста. Спецификация доменной системы — RFC 1035
IP-адрес (ай-пи-адрес) — уникальный сетевой адрес узла в компьютерной сети, построенной по протоколу IP. В сети Интернет требуется глобальная уникальность адреса; в случае работы в локальной сети требуется уникальность адреса в пределах сети. В версии протокола IPv4 IP-адрес имеет длину 4 байта, а в версии протокола IPv6 IP-адрес имеет длину 16 байт.
Администратор: Командная строка
Если ввести в адресную строку браузера -145.255.14.187
Хотя IP для имени — google.com, сервер Google, по IP определил, что вы из России и перевёл на русскую версию поисковой системы.
На предыдущей странице после ввода команды httpd.exe -S
была получена — Ошибка синтаксиса в строке 10 C: /Apache24/conf/extra/httpd-userdir.conf:
Неверная команда «UserDir», возможно, опечатка или заданный модуль не входит в конфигурацию сервера
Файл hosts находится в C:\WINDOWS\system32\drivers\etc\hosts
В каталоге C:\WINDOWS\system32\drivers\etc\ (%WinDir%\System32\Drivers\Etc) откройте в приложение «Блокнот» файл hosts
Можно и из командной строки
C:\Windows\system32>notepad C:\Windows\System32\drivers\etc\hosts
Этот файл содержит сопоставления IP-адресов именам узлов. каждый
Запись должна храниться на отдельной строке.
IP-адрес должен быть размещены в первом столбце, за которым следует соответствующее имя хоста.
IP-адрес и имя узла должны быть разделены по крайней мере одним пробелом.
Поэтому, в секциях — вместо символа » * » нужно указать IP-адрес из из указанного диапазона.
Для обращения к вашему сайту по доменному имени, например — namesite.ru, нужно, в файле конфигурации httpd-vhosts.conf, создать секцию . В директивах которой указать пути к каталогу, подкаталогам и папкам вашего сайта.
Этот файл содержит сопоставления IP-адресов именам узлов.
Каждая запись должна быть на отдельной строке.
IP-адрес должен быть помещен в первой колонке, за которым следует соответствующее имя хоста.
IP-адрес и имя узла должны быть разделены по крайней мере одним пробелом
Символ ‘#’ — это знак комментария. Записи после него игнорируются. Можно использовать после доменного имени.
localhost — («локальный хост», этот компьютер) — стандартное, официально зарезервированное, доменное имя для частных IP-адресов.
То есть, ни один сайт, в сети WWW, не может иметь доменное имя localhost и IP-адрес из указанного диапазона 127.0.0.1 — 127.255.255.255 (RFC 2606).
Использование адреса 127.0.0.1 позволяет устанавливать соединение и передавать информацию для программ-серверов, работающих на том же компьютере, что и программа-клиент, независимо от конфигурации аппаратных сетевых средств компьютера (не требуется сетевая карта, модем, и прочее коммуникационное оборудование, интерфейс реализуется при помощи драйвера псевдоустройства в ядре операционной системы). Таким образом, для работы клиент-серверных приложений на одном компьютере не требуется изобретать дополнительные протоколы и дописывать программные модули.
Обычно адресу 127.0.0.1 однозначно сопоставляется имя хоста «.localhost»
— управление доступом к каталогам пользователей.
На реальных сайтах хостинг провайдеров каталоги для сайтов пользователей обычно называются:
Используемое в данном примере доменное имя — namesite.ru (имясайта.ru) пока, чтобы не повлечь возникновение дополнительных ошибок, не изменяйте на своё. Это можно будет сделать позднее.
Примеры в документации Apache используют каталоги /www/htdocs и /www/docs. Создайте на диске C:/ каталог — www и в нём подкаталог для размещения сайтов. Например — docs
Resolve host name to an ip address
I developed a client/server simulation application. I deployed client and server on two different Windows XP machines. Somehow, the client is not able to send requests to the server.
I tried below options:
Pinged server machine successfully from client using ip-address.
Pinged client machine successfully from server using ip-address.
Checked netstat command line tool from both machines. Server is in LISTENING mode and client is in SYS_SENT mode. But the foreign address it is using to send is host name not the ip address.
Pinged server machine unsuccessfully using host name from client.
Pinged client machine successfully using host name from server.
I feel the problem is when the client is trying to connect to the server using the host name.
Could you please let me know how to force an application to use an ip address instead of a host name? Is there any other way to map the host name to an ip address?
5 Answers 5
Go to your client machine and type in:
substituting the real host name of your server for server.company.com , of course.
That should tell you which DNS server your client is using (if any) and what it thinks the problem is with the name.
To force an application to use an IP address, generally you just configure it to use the IP address instead of a host name. If the host name is hard-coded, or the application insists on using a host name in preference to an IP address (as one of your other comments seems to indicate), then you’re probably out of luck there.
However, you can change the way that most machine resolve the host names, such as with /etc/resolv.conf and /etc/hosts on UNIXy systems and a local hosts file on Windows-y systems.
Try tracert to resolve the hostname. IE you have Ip address 8.8.8.8 so you would use; tracert 8.8.8.8
You could use a C function getaddrinfo() to get the numerical address — both ipv4 and ipv6. See the example code here
This is hard to answer without more detail about the network architecture. Some things to investigate are:
- Is it possible that client and/or server is behind a NAT device, a firewall, or similar?
- Is any of the IP addresses involved a «local» address, like 192.168.x.y or 10.x.y.z?
- What are the host names, are they «real» DNS:able names or something more local and/or Windows-specific?
- How does the client look up the server? There must be a place in code or config data that holds the host name, simply try using the IP there instead if you want to avoid the lookup.
Windows XP has the Windows Firewall which can interfere with network traffic if not configured properly. You can turn off the Windows Firewall, if you have administrator privileges, by accessing the Windows Firewall applet through the Control Panel. If your application works with the Windows Firewall turned off then the problem is probably due to the settings of the firewall.
We have an application which runs on multiple PCs communicating using UDP/IP and we have been doing experiments so that the application can run on a PC with a user who does not have administrator privileges. In order for our application to communicate between multiple PCs we have had to use an administrator account to modify the Windows Firewall settings.
In our application, one PC is designated as the server and the others are clients in a server/client group and there may be several groups on the same subnet.
The first change was to use the functionality of the Exceptions tab of the Windows Firewall applet to create an exception for the port that we use for communication.
We are using host name lookup so that the clients can locate their assigned server by using the computer name which is composed of a mnemonic prefix with a dash followed by an assigned terminal number (for instance SERVER100-1). This allows several servers with their assigned clients to coexist on the same subnet. The client uses its prefix to generate the computer name for the assigned server and to then use host name lookup to discover the IP address of the assigned server.
What we found is that the host name lookup using the computer name (assigned through the Computer Name tab of the System Properties dialog) would not work unless the server PC’s Windows Firewall had the File and Printer Sharing Service port enabled.
So we had to make two changes: (1) setup an exception for the port we used for communication and (2) enable File and Printer Service in the Exceptions tab to allow for the host name lookup.