How to flush cache for socket.gethostbyname response?

陌路散爱 提交于 2019-12-09 17:23:25

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/6928378/how-to-flush-cache-for-socket-gethostbyname-response

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