2006-11-30 23:23:39 +00:00
|
|
|
|
|
|
|
# adapted from nattraverso.ipdiscover
|
|
|
|
|
2006-12-03 02:37:31 +00:00
|
|
|
import socket
|
2006-11-30 23:23:39 +00:00
|
|
|
from twisted.internet import reactor
|
|
|
|
from twisted.internet.protocol import DatagramProtocol
|
|
|
|
|
2006-11-30 23:39:38 +00:00
|
|
|
def get_local_ip_for(target='A.ROOT-SERVERS.NET'):
|
2006-11-30 23:23:39 +00:00
|
|
|
"""Find out what our IP address is for use by a given target.
|
|
|
|
|
2006-12-03 02:37:31 +00:00
|
|
|
Returns a string that holds the IP address which could be used by
|
|
|
|
'target' to connect to us. It might work for them, it might not.
|
2006-11-30 23:23:39 +00:00
|
|
|
"""
|
2007-03-08 01:21:42 +00:00
|
|
|
try:
|
|
|
|
target_ipaddr = socket.gethostbyname(target)
|
|
|
|
except socket.gaierror:
|
|
|
|
return "127.0.0.1"
|
2006-11-30 23:23:39 +00:00
|
|
|
udpprot = DatagramProtocol()
|
|
|
|
port = reactor.listenUDP(0, udpprot)
|
|
|
|
udpprot.transport.connect(target_ipaddr, 7)
|
|
|
|
localip = udpprot.transport.getHost().host
|
2006-12-03 02:37:31 +00:00
|
|
|
port.stopListening() # note, this returns a Deferred
|
2006-11-30 23:23:39 +00:00
|
|
|
return localip
|
2006-12-03 02:37:31 +00:00
|
|
|
|