如何使用Python创建一个非常简单的DNS服务器?

时间:2015-11-04 20:38:41

标签: python dns server

我只想创建一个侦听请求的DNS服务器,并始​​终返回相同的特定IP。我使用Python ....

1 个答案:

答案 0 :(得分:6)

看看dnslib模块,特别是dnslib.server

    >>> class TestResolver:
    ...     def resolve(self,request,handler):
    ...         reply = request.reply()
    ...         reply.add_answer(*RR.fromZone("abc.def. 60 A 1.2.3.4"))
    ...         return reply
    >>> resolver = TestResolver()
    >>> server = DNSServer(resolver,port=8053,address="localhost",logger=logger,tcp=True)
    >>> server.start_thread()
    >>> a = q.send("localhost",8053,tcp=True)
    Request: [...] (tcp) / 'abc.def.' (A)
    Reply: [...] (tcp) / 'abc.def.' (A) / RRs: A
    >>> print(DNSRecord.parse(a))
    ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: ...
    ;; flags: qr aa rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
    ;; QUESTION SECTION:
    ;abc.def.                       IN      A
    ;; ANSWER SECTION:
    abc.def.                60      IN      A       1.2.3.4
    >>> server.stop()