1 ## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved
2 # see LICENSE.txt for license information
6 from twisted.python import log
8 isLocal = re.compile('^(192\.168\.[0-9]{1,3}\.[0-9]{1,3})|'+
9 '(10\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})|'+
10 '(172\.0?([1][6-9])|([2][0-9])|([3][0-1])\.[0-9]{1,3}\.[0-9]{1,3})|'+
11 '(127\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})$')
13 def findMyIPAddr(addrs, intended_port):
14 log.msg("got addrs: %r" % (addrs,))
18 ifconfig = os.popen("/sbin/ifconfig |/bin/grep inet|"+
19 "/usr/bin/awk '{print $2}' | "+
20 "sed -e s/.*://", "r").read().strip().split('\n')
24 # Get counts for all the non-local addresses returned
27 if not isLocal.match(addr):
28 addr_count.setdefault(addr, 0)
31 local_addrs = addr_count.keys()
32 if len(local_addrs) == 1:
33 my_addr = local_addrs[0]
34 log.msg('Found remote address from ifconfig: %r' % (my_addr,))
36 # Get counts for all the non-local addresses returned
40 if not isLocal.match(addr[0]):
41 addr_count.setdefault(addr[0], 0)
42 addr_count[addr[0]] += 1
43 port_count.setdefault(addr[1], 0)
44 port_count[addr[1]] += 1
46 # Find the most popular address
49 for addr in addr_count:
50 if addr_count[addr] > popular_count:
52 popular_count = addr_count[addr]
53 elif addr_count[addr] == popular_count:
54 popular_addr.append(addr)
56 # Find the most popular port
59 for port in port_count:
60 if port_count[port] > popular_count:
62 popular_count = port_count[port]
63 elif port_count[port] == popular_count:
64 popular_port.append(port)
67 if len(port_count.keys()) > 1:
68 log.msg('Problem, multiple ports have been found: %r' % (port_count,))
69 if port not in port_count.keys():
70 log.msg('And none of the ports found match the intended one')
71 elif len(port_count.keys()) == 1:
72 port = port_count.keys()[0]
74 log.msg('Port was not found')
76 if len(popular_addr) == 1:
77 log.msg('Found popular address: %r' % (popular_addr[0],))
78 if my_addr and my_addr != popular_addr[0]:
79 log.msg('But the popular address does not match: %s != %s' % (popular_addr[0], my_addr))
80 my_addr = popular_addr[0]
81 elif len(popular_addr) > 1:
82 log.msg('Found multiple popular addresses: %r' % (popular_addr,))
83 if my_addr and my_addr not in popular_addr:
84 log.msg('And none of the addresses found match the ifconfig one')
86 log.msg('No non-local addresses found: %r' % (popular_addr,))
89 log.msg("Remote IP Address could not be found for this machine")
93 def ipAddrFromChicken():
95 ip_search = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
97 f = urllib.urlopen("http://www.ipchicken.com")
100 current_ip = ip_search.findall(data)