-## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
-# see LICENSE.txt for license information
+
+"""Some utitlity functions for use in the apt-dht program.
+
+@var isLocal: a compiled regular expression suitable for testing if an
+ IP address is from a known local or private range
+"""
import os, re
from twisted.python import log
+from twisted.trial import unittest
isLocal = re.compile('^(192\.168\.[0-9]{1,3}\.[0-9]{1,3})|'+
'(10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})|'+
log.msg("got addrs: %r" % (addrs,))
my_addr = None
+ # Try to find an address using the ifconfig function
try:
ifconfig = os.popen("/sbin/ifconfig |/bin/grep inet|"+
"/usr/bin/awk '{print $2}' | "+
except:
ifconfig = []
- # Get counts for all the non-local addresses returned
+ # Get counts for all the non-local addresses returned from ifconfig
addr_count = {}
for addr in ifconfig:
if local_ok or not isLocal.match(addr):
addr_count.setdefault(addr, 0)
addr_count[addr] += 1
+ # If only one was found, use it as a starting point
local_addrs = addr_count.keys()
if len(local_addrs) == 1:
my_addr = local_addrs[0]
log.msg('Found remote address from ifconfig: %r' % (my_addr,))
- # Get counts for all the non-local addresses returned
+ # Get counts for all the non-local addresses returned from the DHT
addr_count = {}
port_count = {}
for addr in addrs:
popular_count = port_count[port]
elif port_count[port] == popular_count:
popular_port.append(port)
-
+
+ # Check to make sure the port isn't being changed
port = intended_port
if len(port_count.keys()) > 1:
log.msg('Problem, multiple ports have been found: %r' % (port_count,))
else:
log.msg('Port was not found')
+ # If one is popular, use that address
if len(popular_addr) == 1:
log.msg('Found popular address: %r' % (popular_addr[0],))
if my_addr and my_addr != popular_addr[0]:
return my_addr
def ipAddrFromChicken():
+ """Retrieve a possible IP address from the ipchecken website."""
import urllib
ip_search = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
try:
return current_ip
except Exception:
return []
+
+def uncompact(s):
+ """Extract the contact info from a compact peer representation.
+
+ @type s: C{string}
+ @param s: the compact representation
+ @rtype: (C{string}, C{int})
+ @return: the IP address and port number to contact the peer on
+ @raise ValueError: if the compact representation doesn't exist
+ """
+ if (len(s) != 6):
+ raise ValueError
+ ip = '.'.join([str(ord(i)) for i in s[0:4]])
+ port = (ord(s[4]) << 8) | ord(s[5])
+ return (ip, port)
+
+def compact(ip, port):
+ """Create a compact representation of peer contact info.
+
+ @type ip: C{string}
+ @param ip: the IP address of the peer
+ @type port: C{int}
+ @param port: the port number to contact the peer on
+ @rtype: C{string}
+ @return: the compact representation
+ @raise ValueError: if the compact representation doesn't exist
+ """
+
+ s = ''.join([chr(int(i)) for i in ip.split('.')]) + \
+ chr((port & 0xFF00) >> 8) + chr(port & 0xFF)
+ if len(s) != 6:
+ raise ValueError
+ return s
+
+class TestUtil(unittest.TestCase):
+ """Tests for the utilities."""
+
+ timeout = 5
+ ip = '165.234.1.34'
+ port = 61234
+
+ def test_compact(self):
+ """Make sure compacting is reversed correctly by uncompacting."""
+ d = uncompact(compact(self.ip, self.port))
+ self.failUnlessEqual(d[0], self.ip)
+ self.failUnlessEqual(d[1], self.port)