apppublic/appPublic/iplocation.py

100 lines
2.3 KiB
Python
Raw Normal View History

2021-01-31 14:04:50 +08:00
import os
import sys
2022-02-10 10:44:00 +08:00
from requests import get
2021-01-31 14:04:50 +08:00
from bs4 import BeautifulSoup
from appPublic.http_client import Http_Client
from appPublic.sockPackage import get_free_local_addr
public_headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3100.0 Safari/537.36"
}
2022-02-10 10:44:00 +08:00
def get_outip():
ip = get('https://api.ipify.org').content.decode('utf8')
return ip
def ipip(ip=None):
2021-01-31 14:04:50 +08:00
# ipip.net
2022-02-10 10:44:00 +08:00
if ip is None:
ip = get_outip()
2021-01-31 14:04:50 +08:00
api= f"http://freeapi.ipip.net/{ip}"
hc = Http_Client()
r= hc.get(api, headers=public_headers)
return {
'country':r[0],
'city':r[2]
}
2022-05-09 18:00:16 +08:00
def ip_api_com(ip):
url = f'http://ip-api.com/json/{ip}'
hc = Http_Client()
r = hc.get(url)
r['City'] = r['city']
return r
2022-02-10 10:44:00 +08:00
def iplocation(ip=None):
if ip is None:
ip = get_outip()
2021-01-31 14:04:50 +08:00
# apikey come from
# https://app.apiary.io/globaliptv/tests/runs
# using my github accout
apikey='c675f89c4a0e9315437a1a5edca9b92c'
api = f"https://www.iplocate.io/api/lookup/{ip}?apikey={apikey}",
hc = Http_Client()
r= hc.get(api, headers=public_headers)
return r
2022-02-10 10:44:00 +08:00
def ipaddress_com(ip=None):
if ip is None:
ip = get_outip()
2021-01-31 14:04:50 +08:00
url = f'https://www.ipaddress.com/ipv4/{ip}'
2021-03-18 12:48:42 +08:00
print('ipaddress_com(),url=', url)
2021-01-31 14:04:50 +08:00
hc = Http_Client()
r = hc.get(url, headers=public_headers)
bs = BeautifulSoup(r, 'html.parser')
section = bs.find_all('section')[0]
2021-03-18 12:48:42 +08:00
trs = section.find_all('tr')
d = {}
for tr in trs:
th = tr.find_all('th')[0]
td = tr.find_all('td')[0]
2021-10-19 08:51:08 +08:00
# print(th.contents, td.contents)
2021-03-18 12:48:42 +08:00
if th.contents[0] == 'IP Latitude':
d['lat'] = float(td.contents[0].split(' ')[0])
continue
if th.contents[0] == 'IP Country':
2021-10-19 08:51:08 +08:00
# print('ip country:contents[-1]=', td.contents[-1])
x = td.contents[-1].split('(')[0].strip()
while x[0] <= ' ' or x[0] >= chr(128):
x = x[1:]
d['country'] = x
2021-03-18 12:48:42 +08:00
continue
if th.contents[0] == 'IP Longitude':
d['lon'] = float(td.contents[0].split(' ')[0])
continue
if th.contents[0] == 'IP City':
d['City'] = td.contents[0]
2021-01-31 14:04:50 +08:00
return d
def get_ip_location(ip):
apis = {
2022-05-09 18:00:16 +08:00
"ip-api":ip_api_com,
2021-01-31 14:04:50 +08:00
"ipaddress":ipaddress_com,
"ipip.net":ipip,
"iplocation":iplocation,
}
hc = Http_Client()
for k,v in apis.items():
try:
r = v(ip)
return r
except:
pass
if __name__ == '__main__':
print(get_free_local_addr())
if len(sys.argv) > 1:
info = get_ip_location(sys.argv[1])
print(info)