【问题标题】:Convert dnspython dns.resolver.Answer object to raw bytes reply将 dnspython dns.resolver.Answer 对象转换为原始字节回复
【发布时间】:2021-03-12 15:24:37
【问题描述】:

我使用 dnspython 查询 DNS 服务器并获得响应;我的回复以dns.resolver.Answer 对象的形式出现。 我想使用 python 套接字将此 DNS 回复转发到其他地方,为此我需要此消息的原始形式,如下所示:

b'\x01\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00\x03www\x10googletagmanager\x03com\x00\x00\x01\x00\x01'

我使用了文档和.__dict__,发现dns.resolver.Answer包含:

{'qname': <DNS name www.example.com.>, 'rdtype': <RdataType.A: 1>, 'rdclass': <RdataClass.IN: 1>, 'response': <DNS message, ID 1111>, 'nameserver': '8.8.8.8', 'port': 53, 'canonical_name': <DNS name www.example.com.>, 'rrset': <DNS www.example.com. IN A RRset: [<0.0.0.0>]>, 'expiration': 0000}

很遗憾,没有 DNS 响应的原始字节消息。 我怎样才能,可能使用另一个库,转换 dns.resolver.Answer 到原始字节对象?

【问题讨论】:

    标签: python dns


    【解决方案1】:

    dns.resolver.Answer 建立在收到的 dns.resolver.Message 之上,而 to_wire 确实有一个 to_wire

    如果您查看https://www.dnspython.org/docs/1.16.0/dns.resolver-pysrc.html#Resolver.query 的末尾,您可以看到Answer 对象是如何从Message 计算出来的。但是在https://www.dnspython.org/docs/1.16.0/dns.resolver-pysrc.html#Answer.__init__ 中查看它的init,您可以看到它保留了原始Message(您需要访问消息的标题部分,可用作标志等)

    因此,快速演示将是:

    In [2]: import dns
    
    In [3]: import dns.resolver
    
    In [4]: ans = dns.resolver.query('www.example.com')
    
    In [5]: print ans
    <dns.resolver.Answer object at 0x10b2b0d10>
    
    In [6]: print ans.response
    id 21075
    opcode QUERY
    rcode NOERROR
    flags QR RD RA
    ;QUESTION
    www.example.com. IN A
    ;ANSWER
    www.example.com. 37157 IN A 93.184.216.34
    ;AUTHORITY
    ;ADDITIONAL
    
    In [7]: print type(ans.response)
    <class 'dns.message.Message'>
    
    In [8]: print ans.response.to_wire()
    RS��wwwexamplecom�
                      �%]��"
    
    In [17]: print repr(ans.response.to_wire())
    'RS\x81\x80\x00\x01\x00\x01\x00\x00\x00\x00\x03www\x07example\x03com\x00\x00\x01\x00\x01\xc0\x0c\x00\x01\x00\x01\x00\x00\x91%\x00\x04]\xb8\xd8"'
    
    In [18]: r = ans.response.to_wire()
    
    In [19]: message = dns.message.from_wire(r)
    
    In [20]: print message
    id 21075
    opcode QUERY
    rcode NOERROR
    flags QR RD RA
    ;QUESTION
    www.example.com. IN A
    ;ANSWER
    www.example.com. 37157 IN A 93.184.216.34
    ;AUTHORITY
    ;ADDITIONAL
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-01
      • 2016-04-11
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      • 2018-06-11
      • 2013-01-12
      • 2014-07-24
      相关资源
      最近更新 更多