Skip to content

Instantly share code, notes, and snippets.

@eevmanu
Created February 9, 2024 16:21
Show Gist options
  • Save eevmanu/6a7e44b52d31dc18f12c40f69ed9818e to your computer and use it in GitHub Desktop.
Save eevmanu/6a7e44b52d31dc18f12c40f69ed9818e to your computer and use it in GitHub Desktop.
get city and country via vanilla python using ifconfig.co
import urllib.request
import json
def get_public_ip(url):
try:
req = urllib.request.Request(
url,
headers={'User-Agent': 'curl/7.74.0'}
)
with urllib.request.urlopen(req) as response:
ip = response.read().decode('utf-8').strip()
return ip
except urllib.error.HTTPError as e:
return f"HTTP Error: {e.code}"
except urllib.error.URLError as e:
return f"URL Error: {e.reason}"
except Exception as e:
return f"Error: {e}"
data_as_str = get_public_ip(url='https://ifconfig.co/json')
data_as_dict = json.loads(data_as_str)
print(f"City: {data_as_dict['region_name']}, Country: {data_as_dict['country']}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment