Best strategy for overcoming excessive gethostbyname timeout.
r0g
aioe.org at technicalbloke.com
Fri Nov 27 23:20:45 EST 2009
Gabriel Genellina wrote:
> En Fri, 27 Nov 2009 22:35:36 -0300, r0g <aioe.org at technicalbloke.com>
> escribió:
>
>> gethostbyname ignores setdefaulttimeout.
>>
>> How big a job is it to use non-blocking sockets to write a DNS lookup
>> function with a customisable timeout? A few lines? A few hundred? I'd
>> only need to resolve v4 addresses for the foreseeable.
>
> This guy reports good results using GNU adns to perform asynchronous
> queries:
> http://www.catonmat.net/blog/asynchronous-dns-resolution/
>
> Also, look for pydns. Don't be afraid of its age; it always worked fine
> for me.
>
Thanks Gabriel, that worked a treat when combined with John's SIGALARM
solution :)
For posterity here's the code...
import signal, socket
try:
import DNS
except:
DNS = False
def DNSResolve( s ):
if DNS:
DNS.ParseResolvConf() # Windows?
r = DNS.DnsRequest(name=s,qtype='A')
a = r.req()
return a.answers[0]['data']
else:
return socket.gethostbyname( s )
def dns_timeout(a,b):
raise Exception("Oh Noes! a DNS lookup timeout!")
def canIHasIP( domain_name, timeout=3 ):
signal.signal(signal.SIGALRM, dns_timeout)
signal.alarm( timeout )
try:
ip = DNSResolve( domain_name )
except Exception, exc:
print exc
return False
signal.alarm(0)
return ip
usage: canIHasIP( domain_name, timeout_in_seconds) i.e.
canIHasIP("google.com",5)
Thanks guys! :D
Roger.
More information about the Python-list
mailing list