Created
July 10, 2022 15:26
-
-
Save omidekz/55ebe5e67a72b42cdb324c71d167340d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from ipaddress import IPv4Address | |
import json | |
from urllib3.poolmanager import PoolManager | |
base_url = 'http://ip-api.com/json/{query}?fields=status,country,countryCode' | |
http = PoolManager(num_pools=20) | |
def _ip_detail(ip: IPv4Address): | |
assert isinstance(ip, IPv4Address), 'wrong ip type' | |
url = base_url.format(query=str(ip)) | |
resp = http.request('GET', url) | |
if resp.status != 200: | |
return | |
data = json.loads(resp.data) | |
if data['status'] == 'faild': | |
return | |
return data | |
def get_country(ip: IPv4Address): | |
d = _ip_detail(ip) or {} | |
return d.get('country', '').lower() | |
def _2ipv4(ip: str): | |
try: | |
r = IPv4Address(ip) | |
return r | |
except: | |
raise ValueError('Invali IPv4') | |
if __name__ == '__main__': | |
print(get_country(_2ipv4(input('enter ip: ').strip()))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment