MCPcopy Index your code
hub / github.com/TheAlgorithms/Python / get_ip_geolocation

Function get_ip_geolocation

web_programming/get_ip_geolocation.py:12–38  ·  view source on GitHub ↗
(ip_address: str)

Source from the content-addressed store, hash-verified

10
11# Function to get geolocation data for an IP address
12def get_ip_geolocation(ip_address: str) -> str:
13 try:
14 # Construct the URL for the IP geolocation API
15 url = f"https://ipinfo.io/{ip_address}/json"
16
17 # Send a GET request to the API
18 response = httpx.get(url, timeout=10)
19
20 # Check if the HTTP request was successful
21 response.raise_for_status()
22
23 # Parse the response as JSON
24 data = response.json()
25
26 # Check if city, region, and country information is available
27 if "city" in data and "region" in data and "country" in data:
28 location = f"Location: {data['city']}, {data['region']}, {data['country']}"
29 else:
30 location = "Location data not found."
31
32 return location
33 except httpx.RequestError as e:
34 # Handle network-related exceptions
35 return f"Request error: {e}"
36 except ValueError as e:
37 # Handle JSON parsing errors
38 return f"JSON parsing error: {e}"
39
40
41if __name__ == "__main__":

Callers 1

Calls 2

jsonMethod · 0.80
getMethod · 0.45

Tested by

no test coverage detected