python twisted - 如何获取客户端IP

时间:2017-03-14 13:17:56

标签: python dns twisted

如何获取连接到此dns服务器的客户端的IP地址。

from twisted.internet import reactor
from twisted.names import client, dns, server


def main():
    """
    Run the server.
    """
    factory = server.DNSServerFactory(
        clients=[client.Resolver(resolv='/etc/resolv.conf')]
    )

    protocol = dns.DNSDatagramProtocol(controller=factory)

    reactor.listenUDP(10053, protocol)
    reactor.listenTCP(10053, factory)

    reactor.run()


if __name__ == '__main__':
    raise SystemExit(main())

提前谢谢你:P

1 个答案:

答案 0 :(得分:0)

from twisted.internet import reactor
from twisted.names import client, dns, server

class PrintClientAddressDNSServerFactory(server.DNSServerFactory):
    def buildProtocol(self, addr):
        print("Connection to DNSServerFactory from {}".format(addr))
        return server.DNSServerFactory.buildProtocol(self, addr)

class PrintClientAddressDNSDatagramProtocol(dns.DNSDatagramProtocol):
    def datagramReceived(self, datagram, addr):
        print("Datagram to DNSDatagramProtocol from {}".format(addr))
        return dns.DNSDatagramProtocol.datagramReceived(self, datagram, addr)


def main():
    """
    Run the server.
    """
    factory = PrintClientAddressDNSServerFactory(
        clients=[client.Resolver(resolv='/etc/resolv.conf')]
    )

    protocol = PrintClientAddressDNSDatagramProtocol(controller=factory)

    reactor.listenUDP(10053, protocol)
    reactor.listenTCP(10053, factory)

    reactor.run()


if __name__ == '__main__':
    raise SystemExit(main())