How do you get the TTL of a record in the DNS cache on Linux using systemd?

Solution 1:

Make a DNS query against the caching resolver:

dig +noall +answer cloudflare.com A @127.0.0.53

The remaining cache TTL in seconds will be shown as the 2nd field (between name and class). Optionally add +ttlunits to have it formatted.

(Note that you shouldn't need to specify the @127.0.0.53, as it should be the only entry in your resolv.conf when using systemd-resolved; I have included it for demonstration purposes only.)

Whenever a DNS server returns an answer from cache (regardless of it being systemd-resolved or dnsmasq or your router or 8.8.8.8) the answer's TTL field will always indicate the remaining time to live in the server's cache, to ensure that downstream resolvers won't keep the entry cached longer than the original limit. Only authoritative answers may include the full TTL.