socket setdefaulttimeout

Sheila King mathmom at
Sat Aug 13 06:44:27 CEST 2005

I'm doing DNS lookups on common spam blacklists (such as SpamCop..and
others) in an email filtering script. Sometimes, because the DNS server
that is resolving the looksup can go down, it is important to make sure
that the socket doesn't just hang there waiting for a response.

After a recent system upgrade to Python 2.4.1 (from 2.2.2) I thought I
could take advantage of the setdefaulttimeout in the socket module, to
limit the amount of time the sockets take for a lookup.

As a test, I set the default timout ridiculously low. But it doesn't
seem to be having any effect. The sockets will take several seconds to
make the connection and complete the lookups, even though I've set the
timeout to millionths of a second, which I thought would ensure a
timeout (sample script below).

Am I doing something wrong? Do I misunderstand something? Is what I
want to do simply not possible?

Thanks for any tips. Example code follows signature...

Sheila King

import socket
import sys
from time import time, asctime, localtime

debugfile = "socketdebug.txt"

def debug(data):
    timestamp = str(asctime(localtime(time())))
        f = open(debugfile, 'a')
        f.write('\n*** %s ***\n' % timestamp)
        f.write('%s\n' % data)  # 24-Dec-2003 -ctm- removed one
    except IOError:
        # do nothing if the file cannot be opened

IPaddy = ''

if IPaddy:
    IPquads = IPaddy.split('.')
    reverseIP = '.'.join(IPquads)

    bl_list = { '' : 'IP Address %s Rejected - see:' % IPaddy, \
                '' : 'IP Address %s Rejected - see:' % IPaddy, \
                '' : 'IP Address %s Rejected - see:' % IPaddy}

    timing_done = 0
    start_time = time()
    for host in bl_list.keys():
        if host in bl_list.keys():
            IPlookup = "%s.%s" % (reverseIP, host)
                debug("  IPlookup=%s=" % IPlookup)
                resolvesIP = socket.gethostbyname(IPlookup)
                debug("  resolvesIP=%s=" % resolvesIP)
                if resolvesIP.startswith('127.'):
                    end_time = time()
                    elapsed_time = end_time - start_time
                    timing_done = 1
                    debug("Time elapsed for rDNS on bl_list: %f secs" %
                    debug("exiting--SPAM! id'd by %s" % host)
                    print bl_list[host]
            except socket.gaierror:
    if not timing_done:
        end_time = time()
        elapsed_time = end_time - start_time
        debug("2nd try:Time elapsed for rDNS on bl_list: %f secs" %

More information about the Python-list mailing list