How to flush cache for socket.gethostbyname response?

人走茶凉 提交于 2019-12-04 04:34:59

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!