|
| 1 | +import requests |
| 2 | + |
| 3 | + |
| 4 | +# Function to get geolocation data for an IP address |
| 5 | +def get_ip_geolocation(ip_address: str) -> str: |
| 6 | + try: |
| 7 | + # Construct the URL for the IP geolocation API |
| 8 | + url = f"https://ipinfo.io/{ip_address}/json" |
| 9 | + |
| 10 | + # Send a GET request to the API |
| 11 | + response = requests.get(url) |
| 12 | + |
| 13 | + # Check if the HTTP request was successful |
| 14 | + response.raise_for_status() |
| 15 | + |
| 16 | + # Parse the response as JSON |
| 17 | + data = response.json() |
| 18 | + |
| 19 | + # Check if city, region, and country information is available |
| 20 | + if "city" in data and "region" in data and "country" in data: |
| 21 | + location = f"Location: {data['city']}, {data['region']}, {data['country']}" |
| 22 | + else: |
| 23 | + location = "Location data not found." |
| 24 | + |
| 25 | + return location |
| 26 | + except requests.exceptions.RequestException as e: |
| 27 | + # Handle network-related exceptions |
| 28 | + return f"Request error: {e}" |
| 29 | + except ValueError as e: |
| 30 | + # Handle JSON parsing errors |
| 31 | + return f"JSON parsing error: {e}" |
| 32 | + |
| 33 | + |
| 34 | +if __name__ == "__main__": |
| 35 | + # Prompt the user to enter an IP address |
| 36 | + ip_address = input("Enter an IP address: ") |
| 37 | + |
| 38 | + # Get the geolocation data and print it |
| 39 | + location = get_ip_geolocation(ip_address) |
| 40 | + print(location) |
0 commit comments