在 Python 中使用客户端子网选项解析 dns (edns)

Resolve dns (edns) with client subnet option in Python

我正在 Python 中寻找一个实现,它允许我使用 DNS (EDNS) "client sub options" 的扩展来解析 DNS 地址。此选项可为内容交付系统提供更好的 DNS 解析 - 并最终实现更快的互联网路由。此处更好地解释了动机:http://www.afasterinternet.com/howitworks.htm

它的另一个名字是 "vandergaast-edns-client-subnet"

此处提供了挖掘的实现: https://www.gsic.uva.es/~jnisigl/dig-edns-client-subnet.html

我正在寻找可以实现相同功能的 python 实现。

存在 python 实现: 它是 dnspython 的扩展(http://www.dnspython.org/) that can be found here: https://github.com/opendns/dnspython-clientsubnetoption

  1. pip 安装 dnspython
  2. git 从 github
  3. 克隆 repo
  4. 使用这个命令:

    python clientsubnetoption.py (name-server) (host to query>) -s (client-ip) -m 32

  5. 请注意,repo 实际上并没有打印结果。它只是一个测试器,所以它只发出 "success" 或 "failure"。要获得实际结果,您需要修改 python 代码以打印来自 DNS 服务器的响应。

我是 dnspython-clientsubnet 的 developer/maintainer。它旨在在您的代码中用作 dnspython 的添加剂。我刚刚发布了 2.0.0 版(在尝试做你想做的事之后),这让一切变得更容易

  1. pip install clientsubnetoption(适用于 Python2 和 Python3)
  2. 导入 clientsubnetoption 和您需要的依赖项:

    import dns
    import clientsubnetoption
    
  3. 使用您想要的信息设置您的 ClientSubnetOption

    cso = clientsubnetoption.ClientSubnetOption('1.2.3.4')
    
  4. 创建您的 DNS 数据包:

    message = dns.message.make_query('google.com', 'A')
    
  5. 添加 edns 选项:

    message.use_edns(options=[cso])
    
  6. 使用 message 进行查询:

    r = dns.query.udp(message, '8.8.8.8')
    
  7. 选项信息现在位于 r.options 并且可以有多个,因此您可能需要遍历它们才能找到 ClientSubnetOption 对象。

    for options in r.options:
        if isinstance(options, ClientSubnetOption):
            # do stuff here
            pass
    

clientsubnetoption.py中的代码是作为单元测试和支持 edns-clientsubnet 的测试工具,而不是因为你必须那样使用它。