Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to flush cache for socket.gethostbyname response?

Anyone run into this before:

After updating DNS records..I do a dig for 'test.somedomain.com' I get 167.69.143.234, however when I do a socket.gethostbyname('test.somedomain.com') I get 167.69.6.234.

I'm guessing socket is still using cache...how do I clear it ? or flush it?

My code is very simple:

Linux Termianl

dig test.somedomain.com

Python:

import socket
socket.gethostbyname('test.somedomain.com')

It should be returning the 167.69.143.234 address as that is the updated one in DNS.

like image 798
Jim Avatar asked Aug 03 '11 14:08

Jim


2 Answers

Python's socket.gethostbyname uses the operating system resolver and has no API for clearing its cache. The cache (which may be a caching DNS server used by the operating system or a operating system or standard library component) is a fundamental element of the DNS system and 'the right way' to cope with it is to wait until the record's TTL value expires (operating system should remove the stale value from the cache then). When updating the DNS you should probably have TTL of the old value adjusted earlier.

You could also use a Python DNS implementation, like DNSPython instead of using socket.gethostbyname – you should have the full control over the resolver cache (but not the caches of NS the resolver uses) then. Though, it won't probably fix your problem (with an existing code, I guess).

like image 181
Jacek Konieczny Avatar answered Nov 01 '22 09:11

Jacek Konieczny


DNS is not cached on Linux by default and requires a daemon such as sssd or nscd. You can simply restart the daemon to force pulling in the new address.

Note for Windows users: there is a default cache which can be cleared with ipconfig /flushdns.

Alternatively you may have a hard coded entry in /etc/hosts, check there first. Tools like dig or nslookup will query the DNS server directly and bypass the NSS library subsystem.

like image 30
Steve-o Avatar answered Nov 01 '22 08:11

Steve-o