How to flush cache for socket.gethostbyname response?

Jim picture Jim · Aug 3, 2011 · Viewed 11.9k times · Source

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.

Answer

Jacek Konieczny picture Jacek Konieczny · Aug 3, 2011

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).