首页 > 解决方案 > 将 dnspython dns.resolver.Answer 对象转换为原始字节回复

问题描述

我使用 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 为原始字节对象?

标签: pythondns

解决方案


Adns.resolver.Answer建立在 received 的基础上dns.resolver.Message,它确实有一个to_wire.

如果您查看https://www.dnspython.org/docs/1.16.0/dns.resolver-pysrc.html#Resolver.query的末尾,您可以看到Answer对象是如何从Message. 但是inithttps://www.dnspython.org/docs/1.16.0/dns.resolver-pysrc.html#Answer.__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

推荐阅读