-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathipgetter.py
202 lines (164 loc) · 6.34 KB
/
ipgetter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
#!/usr/bin/env python
"""
This module is designed to fetch your external IP address from the internet.
It is used mostly when behind a NAT.
It picks your IP randomly from a serverlist to minimize request
overhead on a single server
API Usage
=========
>>> import ipgetter
>>> myip = ipgetter.myip()
>>> myip
'8.8.8.8'
>>> ipgetter.IPgetter().test()
Number of servers: 47
IP's :
8.8.8.8 = 47 ocurrencies
Copyright 2014 phoemur@gmail.com
This work is free. You can redistribute it and/or modify it under the
terms of the Do What The Fuck You Want To Public License, Version 2,
as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
Updated by Sean Begley for the ipwatch project (https://github.com/begleysm/ipwatch/)
"""
import re
import random
import socket
import ssl
import json
import os
from datetime import datetime, timedelta
from sys import version_info
PY3K = version_info >= (3, 0)
if PY3K:
import urllib.request as urllib
import http.cookiejar as cjar
else:
import urllib2 as urllib
import cookielib as cjar
__version__ = "0.7"
def myip():
return IPgetter().get_ips()
class IPgetter(object):
'''
This class is designed to fetch your external IP address from the internet.
It is used mostly when behind a NAT.
It picks your IP randomly from a serverlist to minimize request overhead
on a single server
'''
def __init__(self):
JSON_FILENAME = 'serverCache.json'
now = datetime.now()
currentTS = datetime.timestamp(now)
theList = None
if os.path.isfile(JSON_FILENAME):
try:
with open(JSON_FILENAME, 'r') as infile:
theList = json.load (infile)
except:
pass
if (theList is None
or "expiry" not in theList
or "expiryDisplay" not in theList
or "servers" not in theList
or theList["expiry"] is None
or theList["expiryDisplay"] is None
or theList["servers"] is None
or not isinstance(theList["expiry"],float)
or len(str(theList["expiry"])) == 0
or not isinstance(theList["servers"],list)
or len(theList["servers"]) == 0
or theList["expiry"] < currentTS
): # we will go off and get the list again
expiryDate = (now + timedelta(days=90))
theList = dict (expiry = datetime.timestamp(expiryDate)
,expiryDisplay = expiryDate.strftime('%Y-%m-%dT%H:%M:%S')
,servers = []
)
operUrl = urllib.urlopen("https://raw.githubusercontent.com/begleysm/ipwatch/master/servers.json")
if(operUrl.getcode()==200):
data = operUrl.read().decode('utf-8')
theList["servers"] = json.loads(data)
with open(JSON_FILENAME, 'w') as outfile:
outfile.write(json.dumps(theList, indent=4))
else:
print("Error receiving data", operUrl.getcode())
self.server_list = theList["servers"]
theList = None
def get_externalip(self):
'''
This function gets your IP from a random server
'''
myip = ''
for i in range(7):
server = random.choice(self.server_list)
myip = self.fetch(server)
if myip != '':
break
return myip,server
def get_local_ip(self):
# From https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
def get_ips(self):
local_ip = self.get_local_ip()
external_ip, server = self.get_externalip()
return external_ip, local_ip, server
def fetch(self, server):
'''
This function gets your IP from a specific server.
'''
url = None
cj = cjar.CookieJar()
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
opener = urllib.build_opener(urllib.HTTPCookieProcessor(cj), urllib.HTTPSHandler(context=ctx))
opener.addheaders = [('User-agent', "Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0"),
('Accept', "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"),
('Accept-Language', "en-US,en;q=0.5")]
try:
url = opener.open(server, timeout=4)
content = url.read()
# Didn't want to import chardet. Prefered to stick to stdlib
if PY3K:
try:
content = content.decode('UTF-8')
except UnicodeDecodeError:
content = content.decode('ISO-8859-1')
m = re.search(
'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)',
content)
myip = m.group(0)
return myip if len(myip) > 0 else ''
except Exception:
return ''
finally:
if url:
url.close()
def test(self):
'''
This functions tests the consistency of the servers
on the list when retrieving your IP.
All results should be the same.
'''
resultdict = {}
for server in self.server_list:
resultdict.update(**{server: self.fetch(server)})
ips = sorted(resultdict.values())
ips_set = set(ips)
print('\nNumber of servers: {}'.format(len(self.server_list)))
print("IP's :")
for ip, ocorrencia in zip(ips_set, map(lambda x: ips.count(x), ips_set)):
print('{0} = {1} ocurrenc{2}'.format(ip if len(ip) > 0 else 'broken server', ocorrencia, 'y' if ocorrencia == 1 else 'ies'))
print('\n')
print(resultdict)
if __name__ == '__main__':
print(myip())