Best strategy for overcoming excessive gethostbyname timeout.

r0g at
Sat Nov 28 04:20:57 CET 2009

John Bokma wrote:
> r0g < at> wrote:
>> It seems gethostbyname asks the OS to resolve the address and the OS
>> uses it's own timeout value ( 25 seconds ) rather than the one provided
>> in setdefaulttimeout. 25 seconds of blocking is way too long for me, I
>> want the response within 5 seconds or not at all but I can see no
>> reasonable way to do this without messing with the OS which naturally I
>> am loathe to do!
> use signal.alarm(time) to send SIGALRM to your process:
> See example at bottom.
> John

Ahh so close. I set the alarm for 3 seconds and it raises the exception,
but only after spending 25 seconds seemingly blocked in gethostbyname.

Here's a snippet, just in case I'm doing it wrong!...

def dns_timeout(a,b):
    raise Exception("DNS timeout")

def send_one_ping(my_socket, dest_addr, ID):
    signal.signal(signal.SIGALRM, dns_timeout)
        dest_addr  =  socket.gethostbyname(dest_addr)
    except Exception, exc:
        print "Exception caught:", exc

Oh well, even if it doesn't work in this case it's really useful to know
about the signal module, I'd never stumbled across it til now, thanks!


More information about the Python-list mailing list