В этой статье мы расскажем, что такое DNS Lookup и как узнать, какие DNS-записи прописаны для домена с помощью утилиты NSLOOKUP.
From simple to complex configurations, there are times you need to check on how your DNS is behaving. Luckily, computers have a built-in utility that can help you do just that. This resource covers useful commands in Windows Command Prompt and PowerShell. It also touches on the differences between the two shells. Ready? Of course you are, that’s why you’re here, right? Oh, who am I kidding? You probably skipped this part and went straight to the commands. Fine. Be that way.
Although the informational RFC 1912 (Section 2.1) recommends that “every Internet-reachable host should have a name” and that “for every IP address, there should be a matching PTR record,” it is not an Internet Standard requirement, and not all IP addresses have a reverse entry.
Что такое NSLOOKUP
Однако посмотреть DNS может не только браузер. Любой пользователь может получить информацию о записях через сервис Whois или через NSLOOKUP. NSLOOKUP — это утилита, которая позволяет через командную строку узнать содержимое DNS. Утилита поможет:
“I’ve tried many dynamic DNS services in the past and Dynu always impresses me.
I can’t get my work done without it at this point and I also appreciate the incredibly fast response time by your support.
I look forward to future developments and I thank you for a great product!”
Jeffrey Oden, Network Engineer
Pennsylvania, USA
“We have been using Dynu email hosting for years now and have never had an issue so far.
Gregory Journe, Project Manager
Lyon, France
“I’ve been using Dynu hostnames as my day-to-day Remote Desktop sessions for a long time, and I’m very happy with it.
The IP Update Client for Windows can run as a System service, so I do not even need to keep my Windows account logged in.
Dynu rocks!”
Kristian Grandahl, Lead Architect Infrastructure Team
Crayon, Norway
We looked at some other providers but Dynu is so far the most stable and affordable one can find.
I recommend Dynu to every customer I have.”
Allan Baker, IT Consultant
Arizona, USA
Текущая версия страницы пока не проверялась опытными участниками и может значительно отличаться от версии, проверенной 21 марта 2021 года; проверки требуют 7 правок.
Для выполнения запроса адрес узла переводится в обратную нотацию, способ перевода зависит от версии IP:
Nslookup (name server lookup) это утилита командной строки, которую можно использовать для диагностики службы DNS, проверки DNS записей и серверов и обнаружения проблем, связанных с разрешением имен в системе DNS. Утилита nslookup изначально разработана в составе пакета BIND и в дальнейшем портирована на Windows. На данный момент утилита Nslookup входит в состав всех поддерживаемых версий Windows.
Утилита Nslookup умеет отправлять запросы на DNS сервер, который указан в настройках вашего сетевого подключения. Этот адрес считается DNS севером по умолчанию (default server). Пользователь может указать адрес любого другого доступного DNS сервера, в результате чего все следующие DNS запросы будут выполнятся уже на нем.
С помощью утилиты nslookup вы можете узнать IP адрес любого сервера по его DNS имени, выполнить обратное преобразование, получить информацию о различных DNS записях домена.
Вы можете использовать утилиту nslookup в интерактивном или не-интерактивном режиме.
Чтобы выполнить DNS запрос с помощью nslookup в неинтерактивном режиме, откройте командную строку и выполните команду:
В данном примере мы запросили IP адрес сервера vmblog.ru. Утилита nslookup обратилась к DNS серверу (указан в строке Server) и он вернул, что этому имени соответствует IP адрес 37.252.2.22.
Такой ответ говорит о том, что ваш DNS сервер доступен и работает штатно, выполняя запросы на разрешение DNS имен.
Если же вы получит ответ вида:
Server: dns1.someserver.comAddress: хх.хх.хх.хх*** dns1.contoso.com can’t find vmblog.ru: Non-existent domain
Это означает, что для данного имени не найдено записей в DNS зоне.
В том случае, если ваш DNS сервер недоступен или не отвечает, вы получите ошибки DNS request timed out.
В этом случае проверьте, указан ли у вас правильный адрес DNS сервера и нет ли проблем с сетевым подключением у провайдера.
Строка Non-authoritative answer (Не заслуживающий доверия ответ)означает, что DNS сервер, который выполнил запрос не является владельцем зоны vmblog.ru (в его базе нет записей об этом домене), а для выполнения разрешения имени использовался рекурсивный запрос к другому DNS серверу.
Можно обратиться к авторитетному серверу, указав его адрес непосредственно в параметрах утилиты nslookup. Например, чтобы выполнить разрешение имени на DNS сервере, который содержит данный домен (authoritative server), используйте команду:nslookup vmblog.ru ns1.vmblog.ruПри запуске nslookup без параметров, утилита переходит в интерактивный режим. В этом режиме вы можете выполнять различные команды. Полный список доступных внутренних команд утилиты nslookup можно вывести, набрав знак вопроса.
Совет. Обратите внимание, что команды утилиты nslookup являются регистрозависимыми.
Для завершения работы с nslookup наберите команду exit и нажмите Enter.
Чтобы найти DNS сервера, которые отвечают за конкретный домен (authoritative servers), выполните команды:
Вы можете выполнить и обратное преобразование (получить DNS имя по IP адресу), для этого просто наберите IP адрес в интерактивной строке nslookup и нажмите Enter.
Вы можете задать тип DNS записей, которые должна вернуть утилита nslookup. Например, чтобы перечислить все почтовые сервера, заданные для определенного домена, выполните команду:
nslookup -type=mx gosuslugi.ru
Не заслуживающий доверия ответ:gosuslugi.ru MX preference = 20, mail exchanger = mx68.gosuslugi.rugosuslugi.ru MX preference = 10, mail exchanger = mx.gosuslugi.rumx68.gosuslugi.ru internet address = 109.207.8.100mx.gosuslugi.ru internet address = 109.207.1.100
Как вы видите, у данного домене 2 MX записи с приоритетами 10 и 20 (Чем меньше число, тем выше приоритет адреса). Если запись MX не отображается, скорее всего они просто не настроены для данного домена.
Чтобы вывести все DNS записи в доменной зоне, выполните команду:
nslookup -type=any gosuslugi.ru
gosuslugi.ru nameserver = ns2.gosuslugi.rugosuslugi.ru nameserver = ns8-l2.nic.rugosuslugi.ru nameserver = ns1.gosuslugi.rugosuslugi.ru nameserver = ns4-l2.nic.rugosuslugi.ru MX preference = 10, mail exchanger = mx.gosuslugi.rugosuslugi.ru MX preference = 20, mail exchanger = mx68.gosuslugi.runs2.gosuslugi.ru internet address = 213.59.255.175ns8-l2.nic.ru internet address = 91.217.21.1ns1.gosuslugi.ru internet address = 109.207.2.218ns4-l2.nic.ru internet address = 91.217.20.1mx.gosuslugi.ru internet address = 109.207.1.100mx68.gosuslugi.ru internet address = 109.207.8.100
Использование опции отладки (debug) позволяет получить дополнительную информацию, содержащуюся в заголовках запросов клиента и ответов сервера (время жизни, флаги, типы записей и т.п.):
Кроме того, эта команда используется для поиска и устранения проблем с DNS. В данном руководстве мы рассмотрим наиболее типичные примеры ее применения.
Команда nslookup может работать в интерактивном и неинтерактивном режимах. Интерактивный режим позволяет пользователю в режиме диалога отправлять DNS-серверу запросы о различных узлах и доменах. Неинтерактивный режим позволяет отправить один запрос об одном узле или домене.
Наиболее распространенные опции и типы аргументов мы рассмотрим ниже в соответствующих примерах.
Получение IP-адреса домена
$ nslookup yandex.ru
Авторитативный и неавторитативный ответы
В приведенном результате присутствует фраза «Non- Authoritative Answer» (неавторитативный ответ).
Авторитативным считается ответ от DNS-сервера, на котором есть полная информация о зоне домена. Во многих случаях на DNS-серверах такой информации нет, они хранят кэш с результатами прошлых запросов, на которые был получен авторитативный ответ. Когда такой сервер получает запрос, он осуществляет поиск в файле кэша и при наличии необходимых данных отправляет их как неавторитативный ответ, как в рассматриваемых нами примерах.
Запрос записи MX
$ nslookup -query=mx redhat.com
Запрос записи NS
Запись NS (Name Server, сервер имен) содержит соответствие доменного имени DNS-серверу, авторитативному для заданного домена. Ее можно получить при помощи опции -query=ns:
$ nslookup -query=ns yandex.ru
Запрос записи SOA
Запись SOA (Start of Authority, начальная запись зоны) содержит информацию о зоне домена, адрес его администратора, серийный номер и т.д. Ее можно получить при помощи опции -query=soa:
$ nslookup -query=soa yandex.ru
Просмотр всех имеющихся записей DNS
При помощи опции -query=any мы можем просмотреть все записи DNS, которые у нас есть для заданного доменного имени:
$ nslookup -type=any google.com
Обратный поиск DNS
$ nslookup 5.255.255.70
Использование конкретного DNS-сервера
Для разрешения доменного имени можно использовать конкретный сервер имен (в данном случае ns1.redhat.com):
$ nslookup redhat.com ns1.redhat.com
Обратите внимание, что в результате отсутствует фраза «Non-authoritative answer», так как ns1.redhat.com обладает всей информацией о зоне для redhat.com.
Изменение номера порта
По умолчанию DNS-серверы используют порт 53, но при необходимости можно указать другой номер порта посредством опции -port:
$ nslookup port 56 yandex.ru
Изменение интервала ожидания ответа
Интервал ожидания ответа по умолчанию можно изменить, указав желаемое значение в секундах с опцией -timeout:
$ nslookup -timeout=10 google.com
Режим отладки
При помощи опции -debug вы можете включить режим отладки:
$ nslookup -debug redhat.com
В режиме отладки при поиске выводится информация о пакетах.
Интерактивный режим
Для входа в интерактивный режим запустите команду nslookup без опций. Далее можно вводить необходимые имена или адреса, а также устанавливать парметры при помощи команды set, например, следующие команды интерактивного режима:
возвращают результат, аналогичный команде
Конечно, при поиске записей для одного имени использовать интерактивный режим бессмысленно. Но при необходимости работы с большим количеством записей он очень удобен, так как позволяет работать в режиме диалога.
Заключение
Мы рассмотрели основы работы с командой nslookup, а также основные типы записей DNS. Для более подробной информации о команде и ее опциях можно обратиться к соответствующей man-странице.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Как определить SOA-запись
SOA-запись (Start of Authority) — начальная запись зоны, которая указывает местоположение эталонной записи о домене. Она содержит в себе контактную информацию лица, ответственного за зону, время кэширования информации на серверах и данные о взаимодействии DNS.
Для определения SOA-записи введите команду:
nslookup –type=SOA site.ru
Где site.ru ― нужный домен.
Как изменить интервал ожидания
Когда интернет слабый, для ответа сервера нужно больше времени, чем обычно. Если ответ не приходит в течение 5 секунд, запрос либо повторяется, либо появляется ошибка. Чтобы ответ от сервера успел дойти, нужно увеличить время ожидания. Для этого введите команду:
nslookup –timeout=10 site.ru
- 10 ― это количество секунд, за которое должен прийти ответ,
- site.ru ― нужное доменное имя.
The modern “reverse DNS lookup” should not be confused with the now-obsolete “inverse query” (IQUERY) mechanism specified in RFC 1035:
Выполнение обратного запросаПравить
PTR-записи не требуют какой-либо специальной обработки, это простые записи, подобные CNAME, которые определяют псевдонимы.
DNS-запись in-addr.arpa выглядит так:
56.34.12.10.in-addr.arpa. IN PTR host1.example.net.
DNS-запись ip6.arpa выглядит так:
5.4.3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa. IN PTR host1.example.net.
Это будет означать, что IPv6-адресу 2001:0db8::1:2345 соответствует имя узла host1.example.net.
При использовании бесклассовой адресации возникает проблема с делегированием отдельных подсетей, не совпадающих по размеру с классом (то есть с поддоменом очередного уровня).
Для решения этой проблемы был создан RFC 2317, описывающий делегирование поддоменов in-addr.arpa в бесклассовой адресации.
Для делегирования диапазонов адресов IPv6 используется доменная зона ip6.arpa.
The nslookup command is helpful in diagnosing issues with DNS name resolution. This command is comparable to Mac or Linux’s dig function. It can find the IP address of a host or perform a reverse DNS lookup (to find the domain name of an IP). Nslookup can also provide information on DNS records for your domain.
In this example, I did a simple request for the IP address for DNS Made Easy. In response, I received the IPv6 and IPv4 address for the domain. The reason it says “non-authoritative answer” is because I’m using a recursive server for the query.
Windows Command Prompt vs Windows PowerShell
There are several ways to start Windows Command Prompt. One way is to click on the search icon in your taskbar and type “command prompt” or “cmd.” This should put the app at the top of the search window under “Best match.”
If you like keyboard shortcuts like I do, you can press Win + R to pull up the Run command. Type cmd and click okay. Boom, you’re in!
You can access PowerShell in the exact same way as Windows Command Prompt. Instead of typing cmd, you would type PowerShell in the Search or Run Command window. Using the search option is where things differ. If you take the search route, you will see an option for Windows PowerShell and PowerShell ISE. In this resource, I’ll be using the basic Windows PowerShell.
Did you know?: PowerShell ISE is a host application for PowerShell. ISE stands for Integrated Scripting Environment. This option provides an interface, whereas standard PowerShell looks more like Command Prompt.
Как узнать MX-запись
При создании электронной почты в ресурсных записях прописывают .
Для определения MX-записей введите команду:
nslookup –type=MX site.ru
Перед вами появится вывод:
DNS MX lookup
Set Command
Let’s say you want to find the nameserver for a domain or set a specific parameter in your command line. For this, you would use the Windows set command. Here’s an example:
(press enter after each command)
The result should look something like this:
DNS Debug Command
To get additional details about your domain’s DNS, you can use the debug command. This will provide the header information of DNS server requests (see screenshot below).
Ping Command
For network diagnostics, you can run a ping command in CMD. A ping measures the latency of a connection for a target location. For demonstration purposes, I’ll run a ping test using 8.8.8.8, Google’s public DNS address.
You now have the round trip time of how long it takes to get a response from the pinged server.
Traceroute Command
What the command is doing is verifying the route packets take to arrive at their destination. The different stops listed are also called hops. Along with the number of hops, you can see the query resolution time. This information can help you improve your DNS speed or identify problematic routers.
Tip: Command Prompt keeps a history of recent commands. If you need to see a command entered earlier in a session, just hit the up arrow key to scroll through them. See the Gif below for an example of how this works.
Windows Command Prompt Commands For DNS
Okay, now for the really good stuff! Here’s several Windows CMD commands that can help troubleshoot or verify your DNS. Don’t worry. I have a very active imagination. I’ll pretend that you didn’t skip all my hard work above and come straight here.
DNS Commands for Windows PowerShell
If Windows PowerShell is your preferred utility, this section is for you. These are the PowerShell equivalents of the above Window Commands:
Nslookup – Resolve-DnsName in PowerShell
Nslookup in PowerShell = Resolve-DnsName
Tip: To save time in PowerShell, type the first few letters of a cmdlet and then press tab to autofill the rest. For example, if you type “reso” and then hit tab (reso + tab), PowerShell will populate Resolve-DnsName. This works the same with other cmdlets like Test-Connection. Start typing “test-con” then hit tab for Test-Connection, etc.”
DNS Record Lookup in Windows PowerShell
PowerShell uses its Resolve-DnsName cmdlet for record lookups. To specify what record, you must add “-type” to complete the cmdlet.
Notice that when I entered -Type or -type, the cmdlet ran the same, so this is not case-sensitive
Ping Command in PowerShell
Ping in PowerShell = Test-Connection
The results look different, but you still see the source (computer name) and the hops, as well as the time it took to receive a response.
Traceroute in PowerShell
Reverse DNS lookups for IPv4 addresses use the special domain in-addr.arpa. In this domain, an IPv4 address is represented as a concatenated sequence of four decimal numbers, separated by dots, to which is appended the second level domain suffix .in-addr.arpa. The four decimal numbers are obtained by splitting the 32-bit IPv4 address into four octets and converting each octet into a decimal number. These decimal numbers are then concatenated in the order: least significant octet first (leftmost), to most significant octet last (rightmost). It is important to note that this is the reverse order to the usual dotted-decimal convention for writing IPv4 addresses in textual form.
For example, to do a reverse lookup of the IP address the PTR record for the domain name 4.4.8.8.in-addr.arpa would be looked up, and found to point to dns.google.
If the A record for dns.google in turn pointed back to then it would be said to be forward-confirmed.
Classless reverse DNS method
You can also use the nslookup and set command to verify or troubleshoot DNS records for your domain. This process is the same as the above example, but this time, you’ll specify which record you want to query. You can address any errors or issues you discover from this information quickly. In the screenshot below, I performed a lookup for MX, PTR, and SOA records, but of course, you aren’t limited to only those.
Tip: If you’re checking multiple record types, you don’t need to type “nslookup” for each one. After the initial nslookup command, you can run set commands for each record. This applies even if you start verifying records for another domain.
DNS Record Command Results – Definitions
- Serial – This is the serial number of the zone file
- Refresh – The time a secondary DNS server will take to request new information if a primary server’s serial number has changed
- Rety – If a primary server doesn’t respond to a request, it will reconnect within this timeframe
- Expire – Secondary DNS cache expiration time
- Default TTL – Refers to how long a record is cached before it’s refreshed
Tip: It may be helpful to clear your DNS cache before performing commands. To do this, type: ipconfig/flushdns and then press enter. Your cache should now be cleared.
Как узнать A-запись домена
Где site.ru ― доменное имя, А-запись которого вы хотите узнать.
Вы увидите следующую информацию:
NSLOOKUP: указать DNS-сервер
Reverse DNS Lookup
If you have an IP address and need the domain name, you can do a reverse DNS lookup. This is the same as the above example, just in—you guessed it—reverse:
Как определить NS-записи домена
Утилита NSLOOKUP позволяет определить, какие NS-серверы использует сайт.
nslookup –type=ns site.ru
Где site.ru ― нужное доменное имя.
Перед вами появится список NS:
There is a variety of web-based DNS lookup tools which you can find online. Most of them will give you multiple options for performing your DNS search. What you will need to specify is the domain name or hostname for your website as well as what record type you wish to see results for. The possible record type search options include the Custom MX and A records, NS Records, CNAME Records, SRV Records, TXT Records, AAAA Records, etc.
A similar service is the Reverse DNS lookup option which most of the DNS lookup tools provide. It refers to searching for the domain name which is associated with a particular IP address.
The nslookup command
The nslookup command is probably one of the few commands, which are the same in both Windows and Linux. It is used to check for the DNS records of a domain name, with the A record being the default record it checks for. The advantage of this command is that you can use it even if you have a slow Internet connection, which can prevent you from utilizing an online DNS lookup tool. It also is much faster than the majority of the online-based tools.
NSLOOKUP in Windows
In Windows, to use the NSLOOKUP command, open the Start menu and click on Run. In the new window, type “cmd”. This will open the command prompt. In there, all you have to do is type “nslookup” and after that the domain that you want to check.
To make a query for a different record and not the A record, which is the default one, you will have to specify the exact record with the “set type=” command.
Check the name servers with NSLOOKUP
In Linux, you can start nslookup from the terminal. The syntax is very similar to the Windows’s.
$ nslookup ntchosting.com
Again, by default, the nslookup command will check for the A records of the given domain name. To change the query type, we will again use the “set type=” option.
Check the MX records with NSLOOKUP
ntchosting.com mail exchanger = 10 mx.ntchosting.com.
Authoritative answers can be found from:
ntchosting.com nameserver = ns2.ntchosting.com.
ntchosting.com nameserver = ns1.ntchosting.com.
mx.ntchosting.com internet address = 66.40.34.23
- RFC 1035 — DOMAIN NAMES — IMPLEMENTATION AND SPECIFICATION (англ.)
- RFC 2317 — Classless IN-ADDR.ARPA delegation (англ.)
The most common uses of the reverse DNS include:
Как использовать утилиту NSLOOKUP
В Windows и macOS утилита встроена, поэтому можно сразу переходить в терминал и начинать с ней работать. Для Linux-систем иногда нужна её установка.
Для установки утилиты в CentOS и Ubuntu в терминале введите:
Для установки утилиты в Debian введите:
Теперь можно переходить к работе с утилитой. Если вы хотите сделать несколько запросов NSLOOKUP, можно включить утилиту в интерактивном режиме. Тогда вам не придется каждый раз писать nslookup в командах. Для этого введите:
Чтобы выйти из интерактивного режима, введите exit.
DNS Lookup Tool
Online resources are also excellent for troubleshooting DNS. These tools are especially useful as they’re accessible from anywhere and on any device. For instance, the DNS Lookup Tool by Constellix (our sister company) can retrieve DNS records and run checks based on geographic location. It will also query against any nameserver you specify. The records supported are A, AAAA, CNAME, MX, TXT, NS, SOA, and SRV.
There are some additional perks to using Constellix’s DNS Lookup tool. You can run checks against different domains and/or nameservers in the same session. Results can be filtered by domain, record type, resolver, or location, and you can expand or minimize each check. You can also copy the URL of the results and email it to your team, which is convenient and a huge timesaver.
It’s All in a Shell
With the above options, you can verify your DNS and troubleshoot issues. Key points: Command Prompt, PowerShell, and online DNS tools provide nameserver, record instructions, and other DNS information, but they operate differently. CMD uses single-line commands, whereas PowerShell uses cmdlets and can run batch commands. Resources like Constellix’s online DNS Lookup tool run checks based on the details you enter.
Of course, this is nowhere near a comprehensive guide to Command Prompt or PowerShell. They can both do much more. Below are several links that can help deepen your understanding of either utility.
If you liked this, you might find these helpful:
Windows CMD commands list
PowerShell Cmdlets List
Introducing Windows PowerShell
- “RFC 1035 — Domain names – implementation and specification”. November 1987. Retrieved .
- “RFC 3425 — Obsoleting IQUERY”. November 2002. Retrieved .
- G. Huston (August 2005). Deprecation of “ip6.int”. Network Working Group IETF. doi:. BCP 109. RFC 4159.
- S. Cheshire; M. Krochmal (February 2013). DNS-Based Service Discovery. IETF. sec. 11. doi:. ISSN 2070-1721. RFC 6763.
- reference page from AOL Archived December 10, 2006, at the Wayback Machine
Что значит authoritative и non-authoritative
В ответе на любую команду утилита показывает, с какого сервера была получена информация. Ответ приходит от серверов двух типов:
- authoritative,
- non-authoritative.
Authoritative answer (авторитетный ответ) – это ответ, который получен от основного (официального) сервера. Non-authoritative answer (неавторитетный ответ) – это ответ от промежуточного сервера. Например, на скриншотах из нашей статьи можно увидеть, что ответ приходил от non-authoritative сервера:
Обратите внимание! На промежуточном сервере может храниться кэшированная копия DNS. Если запись DNS была изменена недавно, кэшированная копия может содержать неактуальную информацию.