Ticket #5596: gethostbyname-exit-5596.patch

File gethostbyname-exit-5596.patch, 1.5 KB (added by Richard Wall, 8 years ago)

A patch which postpones the lookup until the reactor has started

  • doc/names/examples/gethostbyname.py

    === modified file 'doc/names/examples/gethostbyname.py'
     
    55
    66"""
    77Returns the IP address for a given hostname.
     8
    89To run this script:
    910$ python gethostbyname.py <hostname>
    1011e.g.:
    1112$ python gethostbyname.py www.google.com
     13
     14This script does a host lookup using the default Twisted Names
     15resolver.
     16
     17The default Twisted Names resolver is a chained resolver, which
     18attempts to lookup a name using:
     19 * local hosts file
     20 * memory cache of previous lookup results
     21 * system wide recursive DNS servers
     22
     23The hosts file lookup is synchronous, which means that the deferred
     24response can run its callbacks before the reactor is started.
     25
     26To ensure that the reactor is started and stopped in the correct
     27order, we use reactor.callWhenRunning to postpone the host lookup
     28until after the reactor has started.
    1229"""
    1330import sys
    1431from twisted.names import client
    1532from twisted.internet import reactor
    1633
     34
    1735def gotResult(result):
    1836    print result
    19     reactor.stop()
     37
    2038
    2139def gotFailure(failure):
    2240    failure.printTraceback()
    23     reactor.stop()
    24 
    25 d = client.getHostByName(sys.argv[1])
    26 d.addCallbacks(gotResult, gotFailure)
    27 
     41
     42
     43def startLookup():
     44    d = client.getHostByName(sys.argv[1])
     45    d.addCallbacks(gotResult, gotFailure)
     46    d.addBoth(lambda ign: reactor.stop())
     47
     48
     49reactor.callWhenRunning(startLookup)
    2850reactor.run()