netutil.py
1.2 KB
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020-02-16 11:41
# @Author : Lemon
# @File : netutil.py
# @Software: PyCharm
import requests
def _getip_text(url):
try:
r = requests.get(url, headers={"User-Agent": 'curl/7.54.0'}, timeout=1)
if r.status_code == 200:
return {"ip": r.text.strip()}
except:
pass
return {}
def getip(source=-1):
ip = None
hosts = [
'http://icanhazip.com/',
'http://ip.sb/',
'http://ip.3322.net',
'http://myip.dnsomatic.com/',
'http://whatismyip.akamai.com/',
]
if source == -1:
try:
r = requests.head('https://www.163.com', timeout=1)
ip = r.headers.get('cdn-user-ip', None)
except:
pass
if ip:
return ip
else:
return getip(source + 1)
else:
if source == len(hosts):
return None
ip = _getip_text(hosts[source]).get('ip', None)
if ip:
return ip
else:
return getip(source + 1)
if __name__ == '__main__':
ip = lambda: getip()
for _ in range(10):
if callable(ip):
ip = ip()
print(ip)