Fadhil Abubaker
Fadhil Abubaker

Reputation: 146

Non-blocking DNS resolution

This is something that came up while messing around a bit trying to build a DNS client/server system...

A function such as getaddrinfo or gethostbyname resorts to some sort of DNS resolution to answer queries. I've digged around a lot for source code, but never actually seen a single line of code where a socket is open and communications happen between a DNS server and a client.

My question is this, how do functions such as gethostbyname perform a network operation such as a DNS lookup without blocking while reading on a socket etc..? From a user perspective, gethostbyname seems almost instantaneous in operation...

Upvotes: 1

Views: 2735

Answers (2)

Monah Tuk
Monah Tuk

Reputation: 239

Some WA to async resolving is an using getaddrinfo_a with GAI_NOWAIT option.

Existing implementation at the glibc uses thread-pool to do requests. And, it simple to implement such functionality for systems without getaddrinfo_a support.

Note, that resolving mechanizm does not only operates with DNS servers, it uses, also, /etc/hosts (on Windows: WINDIR/system32/etc/hosts) and other sources, like mDNS and so on. It can be configured via /etc/nsswitch.conf, section hosts:.

This functionality provides by the "plugins" for the NSS subsystem, most of them can be found by prefix libnss_. DNS resolver, AFAIK, located at the libnss_dns.so (/usr/lib/x86_64-linux-gnu/libnss_dns.so on my system), that provides by the glibc (libc6 package on Linux Mint).

So, you should look into plugin implementation to search operation with network.

Upvotes: 2

Steffen Ullrich
Steffen Ullrich

Reputation: 123375

Since these functions directly return the value you asked for (instead of using a callback or returning a promise) and since DNS lookups take time these functions must obviously block. How fast they are depends on lots of factors, like which DNS server they query (local or remote), if the result is already available in the DNS server (i.e. cached from previous lookup) and how fast the upstream DNS server are which are needed to lookup yet unknown names.

Upvotes: 2

Related Questions