DNS Queries from Python?

Steve Holden sholden at holdenweb.com
Fri Sep 8 23:20:46 CEST 2000


Andrew Kuchling wrote:
> 
> Steve Holden <sholden at holdenweb.com> writes:
> > more direct would be helpful.  I don't see a dnslib module :-(
> 
> Not in the standard library... but there *is* Demo/dns/dnslib.py.
> (Any reason dnslib shouldn't be cleaned up and moved into the Lib
> directory?)
> 
> --amk

Thanks: I use the binary distribution on Win98, so didn't see this
until I looked on my Linux machine.  Now added a function which will
return the precedence-sorted list of MX servers for a domain.  It
does exactly what I want.

regards
 Steve

def MXlist(qname="holdenweb.com", server='holden.holdenweb.com'):
    import socket
    protocol = 'udp'
    port = 53
    opcode = dnsopcode.QUERY
    rd = 0
    qtype = dnstype.MX
    m = Mpacker()
    m.addHeader(0,
        0, opcode, 0, 0, rd, 0, 0, 0,
        1, 0, 0, 0)
    m.addQuestion(qname, qtype, dnsclass.IN)
    request = m.getbuf()
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect((server, port))
    s.send(request)
    reply = s.recv(2048)
    u = Munpacker(reply)
    (id, qr, opcode, aa, tc, rd, ra, z, rcode,
        qdcount, ancount, nscount, arcount) = u.getHeader()
    for i in range(qdcount):
        qname, qtype, qclass = u.getQuestion()
    MX = []
    for i in range(ancount):
        name, type, klass, ttl, rdlength = u.getRRheader()
        MX.append([u.get16bit(), u.getname()])
    MX.sort()
    servers = []
    for mx in MX:
        servers.append(mx[1])
    return servers

-- 
Helping people meet their information needs with training and technology.
703 967 0887      sholden at bellatlantic.net      http://www.holdenweb.com/



More information about the Python-list mailing list