]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/util/iputil.py
util.iputil: try to survive not having a global network connection at all
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / util / iputil.py
1
2 # adapted from nattraverso.ipdiscover
3
4 import socket
5 from twisted.internet import reactor
6 from twisted.internet.protocol import DatagramProtocol
7
8 def get_local_ip_for(target='A.ROOT-SERVERS.NET'):
9     """Find out what our IP address is for use by a given target.
10
11     Returns a string that holds the IP address which could be used by
12     'target' to connect to us. It might work for them, it might not.
13     """
14     try:
15         target_ipaddr = socket.gethostbyname(target)
16     except socket.gaierror:
17         return "127.0.0.1"
18     udpprot = DatagramProtocol()
19     port = reactor.listenUDP(0, udpprot)
20     udpprot.transport.connect(target_ipaddr, 7)
21     localip = udpprot.transport.getHost().host
22     port.stopListening() # note, this returns a Deferred
23     return localip
24