Generally, on Linux, one would use the res_init/res_ninit functions to get the system nameserver. I have tried this, but the resulting data gives me a DNS server ip of 127.0.0.53, which is the loopback IP of the systemd-resolved stub resolver. Needless to say, this is not the IP I'm looking for.
More specifically, I tried the following code:
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
int main(int argc, char **argv)
{
struct __res_state dns;
res_ninit(&dns);
uint32_t dnsSrv = dns.nsaddr_list[0].sin_addr.s_addr;
uint8_t *dnsOct = (uint8_t*) &dnsSrv;
printf("DNS: %u.%u.%u.%u\n", dnsOct[0], dnsOct[1], dnsOct[2], dnsOct[3]);
return 0;
}
Which gave me the following output:
DNS: 127.0.0.53
How can I go about getting the actual nameserver IP on a system using systemd-resolved in C/C ?
CodePudding user response:
systemd-resolved
is a D-Bus service. You can reach it via D-Bus and there's a DNS
property which contains the list of current DNS servers.
To test:
$ busctl get-property org.freedesktop.resolve1 /org/freedesktop/resolve1 org.freedesktop.resolve1.Manager DNS
a(iiay) 2 0 2 4 1 1 1 1 0 2 4 8 8 8 8
The data format is described in the org.freedesktop.resolve1 API spec:
Each structure in the array consists of a numeric network interface index, an address family, and a byte array containing the DNS server address (either 4 bytes in length for IPv4 or 16 bytes in lengths for IPv6).
So a(iiay) 2 0 2 4 1 1 1 1 0 2 4 8 8 8 8
would mean 2 entries, AF_INET 1.1.1.1, AF_INET 8.8.8.8.
CodePudding user response:
Use resolvectl
command:
[...]$ resolvectl
Global
Protocols: LLMNR mDNS -DNSOverTLS DNSSEC=no/unsupported
resolv.conf mode: stub
Fallback DNS Servers: 1.1.1.1#cloudflare-dns.com 9.9.9.9#dns.quad9.net 8.8.8.8#dns.google 2606:4700:4700::1111#cloudflare-dns.com 2620:fe::9#dns.quad9.net 2001:4860:4860::8888#dns.google
Link 2 (wlp59s0)
Current Scopes: DNS LLMNR/IPv4 LLMNR/IPv6
Protocols: DefaultRoute LLMNR -mDNS -DNSOverTLS DNSSEC=no/unsupported
Current DNS Server: 2a01:cb1d:4cf:6c00:8e19:b5ff:fe13:65d0
DNS Servers: 192.168.1.1 2a01:cb1d:4cf:6c00:8e19:b5ff:fe13:65d0
...
Check the lines Current DNS Server
& DNS Servers