2006-11-30 23:23:39 +00:00
|
|
|
|
|
|
|
# adapted from nattraverso.ipdiscover
|
|
|
|
|
2007-03-08 01:22:30 +00:00
|
|
|
from cStringIO import StringIO
|
|
|
|
import re
|
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
|
2007-03-08 01:22:30 +00:00
|
|
|
from twisted.internet.utils import getProcessOutput
|
|
|
|
|
|
|
|
def get_local_addresses():
|
|
|
|
"""Return a Deferred that fires with a list of IPv4 addresses (as
|
|
|
|
dotted-quad strings) that are currently configured on this host.
|
|
|
|
"""
|
|
|
|
# eventually I want to use somebody else's cross-platform library for
|
|
|
|
# this. For right now, I'm running ifconfig and grepping for the 'inet '
|
|
|
|
# lines.
|
|
|
|
cmd = "ifconfig"
|
|
|
|
d = getProcessOutput("ifconfig")
|
|
|
|
def _parse(output):
|
|
|
|
addresses = []
|
|
|
|
for line in StringIO(output).readlines():
|
|
|
|
# linux shows: " inet addr:1.2.3.4 Bcast:1.2.3.255..."
|
|
|
|
# OS-X shows: " inet 1.2.3.4 ..."
|
|
|
|
m = re.match("^\s+inet\s+[a-z:]*([\d\.]+)\s", line)
|
|
|
|
if m:
|
|
|
|
addresses.append(m.group(1))
|
|
|
|
return addresses
|
|
|
|
def _fallback(f):
|
|
|
|
return ["127.0.0.1", get_local_ip_for()]
|
|
|
|
d.addCallbacks(_parse, _fallback)
|
|
|
|
return d
|
|
|
|
|
2006-11-30 23:23:39 +00:00
|
|
|
|
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
|
|
|
|