I figured this out.. You have to use client.lookupAllRecords and then test the type of records returned..
#!/usr/bin/python
from twisted.internet import defer, reactor
from twisted.names import client, dns
def got_arg(*args):
for a in args[0][0]:
if a.payload.TYPE == dns.A:
print 'A - ipv4',a.payload
elif a.payload.TYPE == dns.AAAA:
print 'AAAA - ipv6',a.payload
def get_arg(arg):
d = client.lookupAllRecords('www.google.com').addCallback(got_arg)
if __name__ == '__main__':
get_arg('www.google.com')
reactor.run()
EDIT
I realize this solution is insufficient - specifically in the case where the first batch of records only contains a single CNAME pointing to another address..
The reason for this is that the twisted.names.common.extractRecord() looks first for ipv6 addresses and immediately returns them - with no obvious mechanism to override this behavior.
So, I put together a hacky solution for this so that we don't even try to resolve down the chain on ipv6 addresses by making an ugly monkey patch..
#!/usr/bin/python
import socket
from twisted.names import dns
from twisted.names import common
def myExtractRecord(resolver, name, answers, level=10):
if not level:
return None
for r in answers:
if r.name == name and r.type == dns.A:
return socket.inet_ntop(socket.AF_INET, r.payload.address)
for r in answers:
if r.name == name and r.type == dns.CNAME:
result = myExtractRecord(
resolver, r.payload.name, answers, level - 1)
if not result:
return resolver.getHostByName(
str(r.payload.name), effort=level - 1)
return result
# No answers, but maybe there's a hint at who we should be asking about
# this
for r in answers:
if r.type == dns.NS:
from twisted.names import client
r = client.Resolver(servers=[(str(r.payload.name), dns.PORT)])
return r.lookupAddress(str(name)
).addCallback(
lambda (ans, auth, add):
myExtractRecord(r, name, ans + auth + add, level - 1))
common.extractRecord = myExtractRecord
I put that in dnsclient.py and use it in my main prog by:
from twisted.names import client
import dnsclient
If there's a more elegant solution for this, I'm all ears. I think this would be more friendly if getHostByName accepted a mask of dns.A,dns.AAAA,dns.A && dns.AAAA for figuring out which records to walk the tree of.