当前位置: 首页 > 工具软件 > dnscache > 使用案例 >

解决linux下dns缓存问题 dnscache.py

郤玉书
2023-12-01

dnscache.py 的详细代码如下,在linux下,直接“import  dnscache”不用修改其它任何东西,即可拥有如windows下面的dns缓存效果,有必要的话,可以在一个有效时间内,清空一下缓存

 

# -*- encoding: utf-8 -*-
import socket, threading

CON_ONLY_CHECK_IPV4 = True # 是否只采用IPV4查询

#def getaddrinfo(host, port, family=None, socktype=None, proto=None, flags=None): # 函数原型
def _getaddrinfo(host, port, *plist, **pdict): # 代理函数
    dns_key = str((host, port, plist, pdict))
    dns_value = None
    try:
        dns_lock.acquire()
        dns_value = dns_cache.get(dns_key, None)
    finally:
        dns_lock.release()
    if dns_value:
        return dns_value
    if CON_ONLY_CHECK_IPV4:
        if plist:
            plist = list(plist)
            plist[0] = 2
        else:
            pdict['family'] = 2
    dns_value = t_getaddrinfo(host, port, *plist, **pdict)
    try:
        dns_lock.acquire()
        dns_cache[dns_key] = dns_value
    finally:
        dns_lock.release()
    return dns_value

# 清空缓存
def Clear_DNS_Cache():
    try:
        dns_lock.acquire()
        dns_cache.clear()
    finally:
        dns_lock.release()

# 初始化
if not hasattr(socket, 'dns_cached'):
    dns_cache = {}
    dns_lock = threading.Lock()
    t_getaddrinfo = socket.getaddrinfo
    socket.getaddrinfo = _getaddrinfo
    socket.dns_cached = True

 

本文为本人原创,转载请注明出处:http://longzhiwen-478.blog.163.com/blog/

 类似资料: