[Twisted-Python] Handeling unresolved DNS queries?

Jesper Taxbøl jesper at taxboel.dk
Tue Oct 20 15:50:33 EDT 2009

Hi Guys,

Im playing with a dns-cache script, that overrides DNS requests for certain
IP addresses.

I would like to add functionality, so unresolved requests are sent to a
spicific IP. How do I go about doing that?

Is there a negative answer in the (udp) DNS protocol or am I forced to use a

Kind regards


import sys, os
from socket import *
from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor
from twisted.names import dns, client, server
import time

LOGFILE = 'dnsfilter.log'

def allowip(ip):
    return True

class Log:
    """file like for writes with auto flush after each write
    to ensure that everything is logged, even during an
    unexpected exit."""
    def __init__(self, f):
        self.f = f
    def write(self, s):

if __name__ == "__main__":
    dns_servers = []
    f = open('/etc/resolv.conf', "r")
    while 1:
        line = f.readline()
        if not line:
        if line[0]!='#':
            s, ns = line.strip().split(' ')
            if s == 'nameserver':
    #redirect outputs to a logfile
    sys.stdout = sys.stderr = Log(open(LOGFILE, 'a+'))

    print 'dnsfilter starting'
    print dns_servers

    #address that traffic is redirected to
    redirect = ''

    greenlist=  ['', \

    class DNSDatagramProtocolTest(dns.DNSDatagramProtocol):
        def writeMessage(self, message, address):
            log = '%s DNS request from: %s\n' % (time.strftime("%m/%d/%y -
%H:%M:%S", time.localtime()) ,address[0])
            for i in range(len(message.answers)):
                x = message.answers[i]
                print x.type
                if x.type==1 and x.payload:
                    if not allowip(address[0]):
                        to_adr = inet_ntoa(x.payload.address)
                        if to_adr in greenlist:
                            log += ' allowed to %s\n'%(to_adr)
                            log += ' not allowed so %s becomes
%s\n'%(to_adr, redirect)
                            x.payload.address = inet_aton(redirect)
                        log += ' to %s\n'%(inet_ntoa(x.payload.address))
            print log
            self.transport.write(message.toStr(), address)

    resolver = client.Resolver(servers=dns_servers)
    f = server.DNSServerFactory(clients=[resolver])
    p = DNSDatagramProtocolTest(f)
    reactor.listenUDP(53, p)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://twistedmatrix.com/pipermail/twisted-python/attachments/20091020/9e55ace4/attachment.htm 

More information about the Twisted-Python mailing list