Yaroslav Yaroslav - 18 days ago 5
C Question

How to make res_query work with dns caching?

I'm using libresolv to perform requests to dns servers.

Also i use local dns cache. (dnsmasq/unbound)

When i use

dig
, for example
dig google.com
, request gets cached and the next request uses cached value.

We can see this in dnsmasq logs:

Nov 9 10:46:46 y dnsmasq[24003]: query[A] google.com from 127.0.0.1
Nov 9 10:46:46 y dnsmasq[24003]: forwarded google.com to **.**.**.**
Nov 9 10:46:46 y dnsmasq[24003]: reply google.com is 173.194.32.165
Nov 9 10:46:46 y dnsmasq[24003]: reply google.com is 173.194.32.160
Nov 9 10:46:49 y dnsmasq[24003]: query[A] google.com from 127.0.0.1
Nov 9 10:46:49 y dnsmasq[24003]: cached google.com is 173.194.32.165
Nov 9 10:46:49 y dnsmasq[24003]: cached google.com is 173.194.32.168


Then i use
res_query
and i get this:

Nov 9 10:50:29 y dnsmasq[24003]: query[MX] google.com from 127.0.0.1
Nov 9 10:50:29 y dnsmasq[24003]: forwarded google.com to **.**.**.**
Nov 9 10:50:29 y dnsmasq[24003]: forwarded google.com to **.**.**.**
Nov 9 10:51:13 y dnsmasq[24003]: query[MX] google.com from 127.0.0.1
Nov 9 10:51:13 y dnsmasq[24003]: forwarded google.com to **.**.**.**
Nov 9 10:51:13 y dnsmasq[24003]: forwarded google.com to **.**.**.**


So it looks like the response from dns server doesn't hit the dns cache and doesn't get cached.

Is there any way to cache request from
res_query
?

This is how I'm making the request to the DNS resolver:

struct __res_state dnsstate;
int rc = res_ninit(&dnsstate);
if (rc < 0) {
return result;
}
dnsstate.retrans = timeout;

int len = res_nquery(&dnsstate, domain.c_str(), ns_c_in, ns_t_mx, nsbuf, sizeof(nsbuf));


I suppose that res_nquery doesn't check local DNS cache, and dig does.

Answer

Both dig and res_nquery() will just send the queries to whatever's in your /etc/resolv.conf file, i.e. your dnsmasq instance. Both will also by default set the RD bit to request recursion.

dnsmasq will then either serve the answers from cache, or go fetch them if the TTL has expired. However to my knowledge there is nothing in the DNS protocol itself (and therefore nothing in the res_nquery settings) that a client can set that will influence that behaviour

Comments