2 """Some utitlity functions for use in the apt-p2p program.
4 @var isLocal: a compiled regular expression suitable for testing if an
5 IP address is from a known local or private range
10 from twisted.python import log
11 from twisted.trial import unittest
13 isLocal = re.compile('^(192\.168\.[0-9]{1,3}\.[0-9]{1,3})|'+
14 '(10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})|'+
15 '(172\.0?([1][6-9])|([2][0-9])|([3][0-1])\.[0-9]{1,3}\.[0-9]{1,3})|'+
16 '(127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})$')
18 def findMyIPAddr(addrs, intended_port, local_ok = False):
19 """Find the best IP address to use from a list of possibilities.
21 @param addrs: the list of possible IP addresses
22 @param intended_port: the port that was supposed to be used
23 @param local_ok: whether known local/private IP ranges are allowed
25 @return: the preferred IP address, or None if one couldn't be found
27 log.msg("got addrs: %r" % (addrs,))
30 # Try to find an address using the ifconfig function
32 ifconfig = os.popen("/sbin/ifconfig |/bin/grep inet|"+
33 "/usr/bin/awk '{print $2}' | "+
34 "sed -e s/.*://", "r").read().strip().split('\n')
38 # Get counts for all the non-local addresses returned from ifconfig
41 if local_ok or not isLocal.match(addr):
42 addr_count.setdefault(addr, 0)
45 # If only one was found, use it as a starting point
46 local_addrs = addr_count.keys()
47 if len(local_addrs) == 1:
48 my_addr = local_addrs[0]
49 log.msg('Found remote address from ifconfig: %r' % (my_addr,))
51 # Get counts for all the non-local addresses returned from the DHT
55 if local_ok or not isLocal.match(addr[0]):
56 addr_count.setdefault(addr[0], 0)
57 addr_count[addr[0]] += 1
58 port_count.setdefault(addr[1], 0)
59 port_count[addr[1]] += 1
61 # Find the most popular address
64 for addr in addr_count:
65 if addr_count[addr] > popular_count:
67 popular_count = addr_count[addr]
68 elif addr_count[addr] == popular_count:
69 popular_addr.append(addr)
71 # Find the most popular port
74 for port in port_count:
75 if port_count[port] > popular_count:
77 popular_count = port_count[port]
78 elif port_count[port] == popular_count:
79 popular_port.append(port)
81 # Check to make sure the port isn't being changed
83 if len(port_count.keys()) > 1:
84 log.msg('Problem, multiple ports have been found: %r' % (port_count,))
85 if port not in port_count.keys():
86 log.msg('And none of the ports found match the intended one')
87 elif len(port_count.keys()) == 1:
88 port = port_count.keys()[0]
90 log.msg('Port was not found')
92 # If one is popular, use that address
93 if len(popular_addr) == 1:
94 log.msg('Found popular address: %r' % (popular_addr[0],))
95 if my_addr and my_addr != popular_addr[0]:
96 log.msg('But the popular address does not match: %s != %s' % (popular_addr[0], my_addr))
97 my_addr = popular_addr[0]
98 elif len(popular_addr) > 1:
99 log.msg('Found multiple popular addresses: %r' % (popular_addr,))
100 if my_addr and my_addr not in popular_addr:
101 log.msg('And none of the addresses found match the ifconfig one')
103 log.msg('No non-local addresses found: %r' % (popular_addr,))
106 log.msg("Remote IP Address could not be found for this machine")
110 def ipAddrFromChicken():
111 """Retrieve a possible IP address from the ipchecken website."""
113 ip_search = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
115 f = urllib.urlopen("http://www.ipchicken.com")
118 current_ip = ip_search.findall(data)
124 """Extract the contact info from a compact peer representation.
127 @param s: the compact representation
128 @rtype: (C{string}, C{int})
129 @return: the IP address and port number to contact the peer on
130 @raise ValueError: if the compact representation doesn't exist
134 ip = '.'.join([str(ord(i)) for i in s[0:4]])
135 port = (ord(s[4]) << 8) | ord(s[5])
138 def compact(ip, port):
139 """Create a compact representation of peer contact info.
142 @param ip: the IP address of the peer
144 @param port: the port number to contact the peer on
146 @return: the compact representation
147 @raise ValueError: if the compact representation doesn't exist
150 s = ''.join([chr(int(i)) for i in ip.split('.')]) + \
151 chr((port & 0xFF00) >> 8) + chr(port & 0xFF)
156 class TestUtil(unittest.TestCase):
157 """Tests for the utilities."""
163 def test_compact(self):
164 """Make sure compacting is reversed correctly by uncompacting."""
165 d = uncompact(compact(self.ip, self.port))
166 self.failUnlessEqual(d[0], self.ip)
167 self.failUnlessEqual(d[1], self.port)