Show dns address linux

Как узнать IP DNS сервера в Linux

DNS (Domain Name System — система доменных имён) является важным элементом сети. Без DNS не работали бы Интернет-браузер, почтовые сервера, стриминговые сервисы и другие.

Задача DNS сообщать IP адрес запрошенного имени хоста (обычно домена веб-сайта).

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

То есть DNS решает проблему, что нам не нужно помнить/знать IP адреса всех сайтов, которые мы посещаем.

DNS это обширная и интересная тема, но в этой заметке мы только поговорим, как узнать, к какому именно DNS серверу делаются запросы с данного компьютера на Linux? То есть мы научимся определять IP адрес используемого DNS сервера.

Имеется несколько способов сделать это, мы рассмотрим самые универсальные, подходящие для Linux, BSD, и других Unix-подобных систем.

Как узнать какой DNS сервер используется

1. Настройки DNS в системе хранятся в файле /etc/resolv.conf, то есть IP адрес DNS сервера можно узнать просто посмотрев этот файл.

С помощью команды cat:

С помощью команды less:

Или с помощью команды grep:

grep "nameserver" /etc/resolv.conf

Все эти команды выведут одинаковые результаты, например в моём случае это:

nameserver 8.8.8.8 nameserver 8.8.4.4

Запись может быть только одна или их может быть несколько. В первую очередь используется первый указанный DNS сервер, если к нему не удаётся получить доступ, то используются запасные DNS (если они указаны).

2. Если вам нужен альтернативный метод (например, вы предполагаете, что настройки DNS изменены сетевым подключением), то вы можете использовать программу dig:

Используемый сервер имён показан в строке начинающейся с ;; SERVER:

А в этом разделе, кстати, вы можете узнать IP адрес любого сайта:

;; ANSWER SECTION: zalinux.ru. 3799 IN A 185.26.122.38

3. Ещё один способ узнать IP адрес сайта, а заодно и IP DNS сервера к которому делаются запросы — с помощью команды nslookup:

В этих строках показан IP используемого DNS сервера:

Server: 8.8.8.8 Address: 8.8.8.8#53

А в этой строке IP адрес интересующего сайта:

Источник

Как посмотреть DNS в Linux

Служба DNS или Domain Name System позволяет превращать легко читаемый адрес сайта в ip адрес сервера на котором расположен этот сайт. Для этого используются DNS серверы, которые содержат таблицы соответствия ip адресов их доменным именам. По умолчанию система получает адрес DNS сервера автоматически по DHCP при подключении к сети.

В этой статье мы разберемся как посмотреть какие DNS серверы используются в Linux.

Читайте также:  Build embedded linux systems

Как посмотреть DNS в Linux

Если вы уже имели опыт настройки сети в Linux, то знаете, что DNS серверы, используемые для резолвинга доменных имен указаны в файле /etc/resolv.conf:

Но в современных дистрибутивах Linux с системой инициализации systemd обычно запущен локальный DNS сервер, адрес которого и прописан в этом файле, а какие сервера используются на самом деле непонятно. В таком случае можно воспользоваться утилитой systemd-resolve:

В самом низу вывода утилиты можно посмотреть DNS в Linux, которые сейчас используются. Информация выводится по каждому сетевому интерфейсу отдельно.

Также для решения подобной задачи можно использовать утилиту nmcli:

Как видите, все очень просто. А чтобы изменить DNS сервер тоже трогать /etc/resolv.conf не желательно, так как он будет автоматически обновляться после перезагрузки. Если вы используете NetworkManager, то можно настроить DNS для сетевого подключения в интерфейсе программы. Или же можно отредактировать файл /etc/systemd/resolved.conf и добавить нужные адреса в секцию Resolve:

sudo vi /etc/systemd/resolved.conf

Как видите, все очень просто. Надеюсь, эта информация была вам полезной.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

3 Ways to check DNS server IP in Linux

DNS servers are an important part of the internet, translating domain names into IP addresses. If your DNS server is not working correctly, you may experience problems loading websites or sending and receiving email. In this blog post, we will discuss three ways to check your DNS server in Linux. We will also provide some tips for troubleshooting DNS problems. Let’s get started!

Check DNS server IP with Dig command in Linux

The best way to check your DNS server is to use the ‘dig’ command. The ‘dig’ command allows you to query DNS servers for information about domains. To use the ‘dig’ command, open a terminal and type the following: dig example.com

This will query the DNS server for information about the domain “example.com”. For example, if you want to query for A records, you would type the following: dig example.com +short

You can replace “example.com” with any domain you want to query. From the following example, we can see that the DNS server is 64.104.76.247 .

dig howtouselinux.com
; > DiG 9.10.6 > howtouselinux.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER ;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1
;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1280
;; QUESTION SECTION:
;howtouselinux.com. IN A
;; ANSWER SECTION:
howtouselinux.com. 0 IN A 162.159.137.9
howtouselinux.com. 0 IN A 162.159.138.9
;; Query time: 138 msec
;; SERVER: 64.104.76.247#53(64.104.76.247)
;; WHEN: Wed Mar 02 21:24:01 CST 2022
;; MSG SIZE rcvd: 78

Check DNS server IP with nslookup command in Linux

The second way to check your DNS server is to use the ‘nslookup’ command. ‘Nslookup’ is a tool that allows you to query DNS servers for information about domains. To use the ‘nslookup’ command, open a terminal and type the following: nslookup example.com

This will query the DNS server for information about the domain “example.com”. You can also query specific records by using the ‘querytype’ parameter. For example, if you want to query for A records, you would type the following: nslookup -query=a example.com

Читайте также:  Восстановление linux acronis true image

The dns server is 64.104.76.247 from the following example.
% nslookup -query=a howtouselinux.com
Server: 64.104.76.247
Address: 64.104.76.247#53
Non-authoritative answer:
Name: howtouselinux.com
Address: 162.159.137.9
Name: howtouselinux.com
Address: 162.159.138.9

Check DNS server IP with /etc/resolv.conf file in Linux

The third way is to check /etc/resolv.conf configuration file. It contains DNS server information we use.

cat /etc/resolv.conf
domain howtouselinux.com
nameserver 64.104.76.247
nameserver 64.104.76.248

We hope this blog post has been helpful in showing you how to check your DNS server in Linux. If you are experiencing DNS problems, be sure to try using these three commands to troubleshoot the issue. Thanks for reading!

Источник

What DNS servers am I using?

The Linux kernel itself is not aware about DNS services. To answer it’s better to know your userland. What distribution are you using? Ubuntu? Debian GNU/Linux? Centos?

14 Answers 14

You should be able to get some reasonable information in:

However, please be aware that (on modern Linuxen) the contents of /etc/nsswitch.conf dictate what name services are used (DNS, LDAP, etc) and in what order. Say fgrep hosts: /etc/nsswitch.conf . If it only references DNS, /etc/resolv.conf is the right place to look for your nameservers. But chances are you’re also using mDNS (aka ZeroConf, aka Avahi, aka Bonjour, etc), etc. In that case, things depend on what you’re using.

This file typically points at 127.0.1.1 on Ubuntu — it’s the local DNS cache server, not the actual upstream.

See the answers by @G32RW or @Lonniebiz for a more robust approach under various circumstances, e.g. when you get an answer like 127.0.0.53

This solution is no more up to date. I find the systemd-resolve —status suggested by @G32RW most up-to-date solution for this problem.

( nmcli dev list || nmcli dev show ) 2>/dev/null | grep DNS 

On Debian, you need to have the network-manager package installed.

This one is usefull if you are using VPN and NetworkManager. Your /etc/resolv.conf will point to your machine, with dnsmasq resolving names as configured by NetworkManager.

nm-tool is not available in newer linuxes. for example it is not in the ‘network-manager’ package of debian 8.

This did not work for me on an Ubuntu VM. nmcli dev show did not have the DNS info. However, systemd-resolve —status did have the real DNS server. unix.stackexchange.com/a/434756

On systems running systemd use:

I think you can also query DNS and it will show you what server returned the result. Try this:

dig yourserver.somedomain.xyz 

And the response should tell you what server(s) returned the result. The output you’re interested in will look something like this:

;; Query time: 91 msec ;; SERVER: 172.xxx.xxx.xxx#53(172.xxx.xxx.xxx) ;; WHEN: Tue Apr 02 09:03:41 EDT 2019 ;; MSG SIZE rcvd: 207 

You can also tell dig to query a specific DNS server by using dig @server_ip

If you use any DNS masking/caching service that is run on your local machine, it will hide the real DNS servers.

Читайте также:  Просмотр имени компьютера linux

This only tells you which server was used for that query. It doesn’t tell you all the DNS servers that your host might use.

Beware that this obviously fails if the DNS server is not available. That’s not a common thing, but I’ve managed to get a bad result or timeout when looking for a DNS server running on IPv6 (using dig -6 ).

Just do an, nslookup . Part of its results include the server that it’s using.

In the example below, it shows that the DNS server used is at 8.8.8.8.

$ nslookup google.com Server: 8.8.8.8 Address: 8.8.8.8#53 Non-authoritative answer: Name: google.com Address: 172.217.22.174 

On a recent Ubuntu, this again points to the local cache server 127.0.0.1 as already hinted at in this comment

In CentOS 7 it quits with error, but it is a vm so I did nslookup google.com in the Windows host and I found the nameserver. Add it in /etc/resolv.conf like: nameserver xx.xx.xx.xx and restart service network , and all is fine. Praise you.

With the new network-manager command nmcli , do this:

nmcli --fields ipv4.dns,ipv6.dns con show [connection_name] 

On newer versions of network-manager (such as in Ubuntu 16.04), the field names are slightly different:

nmcli --fields ip4.dns,ip6.dns con show [connection_name] 

If you don’t know the connection name, use:

nmcli -t --fields NAME con show --active 

For example, on old versions of nmcli :

$ nmcli --fields ip4.dns,ip6.dns con show 'Wired connection 1' IP4.DNS[1]: 172.21.0.13 IP4.DNS[2]: 172.21.0.4 

Returns Error: invalid field ‘ip4.dns’; allowed fields: NAME,UUID,TYPE,TIMESTAMP,TIMESTAMP-REAL,AUTOCONNECT,AUTOCONNECT-PRIORITY,READONLY,DBUS-PATH,ACTIVE,DEVICE,STATE,ACTIVE-PATH.

to get the first DNS SERVER (IP only) :

cat /etc/resolv.conf|grep -im 1 '^nameserver' |cut -d ' ' -f2 
  • cat will output DNS config
  • grep filters only nameserver
  • -i grep ignore case
  • -m 1 grep stop after first match
  • cut take the ip part of the row (second column with ‘ ‘ as separator)

To put DNS ip in an environment variable, you could use as follow:

export THEDNSSERVER=$(cat /etc/resolv.conf|grep -im 1 '^nameserver' |cut -d ' ' -f2) 

To lighten the pipeline even more, capture groups with Perl regexp is very neat, and grep takes a file argument: grep -Pom 1 ‘^nameserver \K\S+’ /etc/resolv.conf . Just wrote up Capture groups with grep perl regular expression

There’s both IPv4 and IPv6 DNS servers. Also, secondary servers exist for a reason. Which one this command returns? Is it advised to take the first one, and just ignore the others?

Using resolvectl

$ resolvectl status | grep -1 'DNS Server' DNSSEC supported: no Current DNS Server: 1.1.1.1 DNS Servers: 1.1.1.1 1.0.0.1 

grep option: -C NUM , -NUM , —context=NUM Print NUM lines of output context.

For compatibility, systemd-resolve is a symbolic link to resolvectl on many distros as for Ubuntu 18.10:

$ type -a systemd-resolve systemd-resolve is /usr/bin/systemd-resolve $ ll /usr/bin/systemd-resolve lrwxrwxrwx 1 root root 10 nov. 15 21:42 /usr/bin/systemd-resolve -> resolvectl $ type -a resolvectl resolvectl is /usr/bin/resolvectl $ file /usr/bin/resolvectl /usr/bin/resolvectl: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=09e488e849e3b988dd2ac93b024bbba18bb71814, stripped 

Источник

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