source: code/getmyip.py @ 133

Last change on this file since 133 was 23, checked in by trishank, 7 years ago

Add pre-release upPIR from June 2011.

File size: 3.0 KB
Line 
1"""
2   Author: Justin Cappos
3
4   Start Date: 27 June 2008
5
6   Description:
7
8   Adapted from repy's emulcomm (part of the Seattle project)
9"""
10
11import socket
12
13
14
15STABLE_PUBLIC_IPS = ["18.7.22.69",      # M.I.T
16                    "171.67.216.8",     # Stanford
17                    "169.229.131.81",   # Berkley
18                    "140.142.12.202"]   # Univ. of Washington
19
20
21
22
23def get_localIP_to_remoteIP(connection_type, external_ip, external_port=80):
24  """
25  <Purpose>
26    Resolve the local ip used when connecting outbound to an external ip.
27 
28  <Arguments>
29    connection_type:
30      The type of connection to attempt. See socket.socket().
31   
32    external_ip:
33      The external IP to attempt to connect to.
34     
35    external_port:
36      The port on the remote host to attempt to connect to.
37 
38  <Exceptions>
39    As with socket.socket(), socketobj.connect(), etc.
40 
41  <Returns>
42    The locally assigned IP for the connection.
43  """
44  # Open a socket
45  sockobj = socket.socket(socket.AF_INET, connection_type)
46
47  try:
48    sockobj.connect((external_ip, external_port))
49
50    # Get the local connection information for this socket
51    (myip, localport) = sockobj.getsockname()
52
53  # Always close the socket
54  finally:
55    sockobj.close()
56
57  return myip
58
59
60
61
62
63# Public interface
64def getmyip():
65  """
66   <Purpose>
67      Provides the external IP of this computer.   Does some clever trickery.
68
69   <Arguments>
70      None
71
72   <Exceptions>
73      As from socket.gethostbyname_ex()
74
75   <Side Effects>
76      None.
77
78   <Returns>
79      The localhost's IP address
80      python docs for socket.gethostbyname_ex()
81  """
82
83  # I got some of this from: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d931cdc326d7032b?hl=en
84  # however, it has been adapted...
85 
86  # Initialize these to None, so we can detect a failure
87  myip = None
88 
89  # It's possible on some platforms (Windows Mobile) that the IP will be
90  # 0.0.0.0 even when I have a public IP and the external IP is up. However, if
91  # I get a real connection with SOCK_STREAM, then I should get the real
92  # answer.
93  for conn_type in [socket.SOCK_DGRAM, socket.SOCK_STREAM]:
94       
95    # Try each stable IP 
96    for ip_addr in STABLE_PUBLIC_IPS: 
97      try:
98        # Try to resolve using the current connection type and
99        # stable IP, using port 80 since some platforms panic
100        # when given 0 (FreeBSD)
101        myip = get_localIP_to_remoteIP(conn_type, ip_addr, 80)
102      except (socket.error, socket.timeout):
103        # We can ignore any networking related errors, since we want to try
104        # the other connection types and IP addresses. If we fail,
105        # we will eventually raise an exception anyways.
106        pass
107      else:
108        # Return immediately if the IP address is good
109        if myip != None and myip != '' and myip != "0.0.0.0":
110          return myip
111
112
113  # Since we haven't returned yet, we must have failed.
114  # Raise an exception, we must not be connected to the internet
115  raise Exception("Cannot detect a connection to the Internet.")
116
117
118if __name__ == '__main__':
119  print getmyip()
Note: See TracBrowser for help on using the repository browser.