From: Brian Warner Date: Thu, 8 Mar 2007 01:22:30 +0000 (-0700) Subject: iputil: add get_local_addresses(), an attempt to enumerate all IPv4 addresses on... X-Git-Url: https://git.rkrishnan.org/vdrive/components/com_hotproperty/provisioning?a=commitdiff_plain;h=18325251bf4672538764be28c2df720b04a8e2f4;p=tahoe-lafs%2Ftahoe-lafs.git iputil: add get_local_addresses(), an attempt to enumerate all IPv4 addresses on this host. This is pretty unix-specific for right now (it calls ifconfig) --- diff --git a/src/allmydata/test/test_iputil.py b/src/allmydata/test/test_iputil.py new file mode 100644 index 00000000..7a064a4f --- /dev/null +++ b/src/allmydata/test/test_iputil.py @@ -0,0 +1,14 @@ + +from twisted.trial import unittest +from allmydata.util.iputil import get_local_addresses + +class ListAddresses(unittest.TestCase): + def test_list(self): + d = get_local_addresses() + def _check(addresses): + self.failUnless(len(addresses) >= 1) # always have localhost + self.failUnless("127.0.0.1" in addresses) + print addresses + d.addCallbacks(_check) + return d + diff --git a/src/allmydata/util/iputil.py b/src/allmydata/util/iputil.py index bfa5b5f9..6c52c64e 100644 --- a/src/allmydata/util/iputil.py +++ b/src/allmydata/util/iputil.py @@ -1,9 +1,36 @@ # adapted from nattraverso.ipdiscover +from cStringIO import StringIO +import re import socket from twisted.internet import reactor from twisted.internet.protocol import DatagramProtocol +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 + def get_local_ip_for(target='A.ROOT-SERVERS.NET'): """Find out what our IP address is for use by a given target.