-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathip_resolver.py
75 lines (51 loc) · 2.03 KB
/
ip_resolver.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
import re
import requests
from requests import Timeout
class IpResolverError(Exception):
"""IpResolver Exceptions"""
pass
class IpResolver:
"""IP resolver.
Parse the IP from a website containing plain text, or web page with a single IP.
"""
def __init__(self, url, alt_url=None):
"""IP resolver.
Parse the IP from a website containing plain text, or web page with a single IP.
:param str url: The resolver URL.
:param str alt_url: Alternative resolver URL.
"""
self.url = url
self.alt_url = alt_url
def resolve_ip(self):
"""Resolve the IP by parsing the content of the resolver URL.
:return: The resolved IP.
:rtype: str
"""
r = None
try:
r = requests.get(self.url, timeout=30.0)
if not r.ok:
if self.alt_url:
print("Main resolver returned and error code HTTP/%s, trying alternate resolver." % str(r.status_code))
r = None
else:
raise IpResolverError("IP resolver returned an error code HTTP/%s." % str(r.status_code))
except Timeout:
if self.alt_url:
print("Main resolver timeout, trying alternate resolver.")
else:
raise IpResolverError("IP resolver timeout.")
if r is None and self.alt_url:
try:
r = requests.get(self.alt_url, timeout=30.0)
if not r.ok:
raise IpResolverError("Alternate IP resolver returned an error code HTTP/%s." % str(r.status_code))
except Timeout:
raise IpResolverError("Alternate IP resolver timeout.")
if not r.content:
raise IpResolverError("Invalid content returned by IP resolver.")
match = re.search("(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", r.text)
if not match:
raise IpResolverError("IP not found in resolver content.")
ip = match.group(1)
return ip