这对我有用
import requests
def get_global_ip():
try:
response = requests.get('https://ipinfo.io/json')
data = response.json()
return data['ip'], data['country'], data['city']
except Exception as e:
print("Error while retrieving location:", e)
return None
global_ip = get_global_ip()
if global_ip:
print("Your global IP address and location:", global_ip)
else:
print("Failed to retrieve the global IP address and location")
或者,如果你知道你的ip,你可以试试这个:
import requests
def get_location(ip):
url = f"http://ip-api.com/json/{ip}"
response = requests.get(url)
data = response.json()
if data['status'] == 'success':
return data['city'], data['country']
else:
return None
my_ip = 'xxx.xxx.xxx.xxx' # global/white ip-address
location = get_location(my_ip)
if location:
city, country = location
print(f"Your city: {city}, country: {country}")
else:
print("It is not possible to get info about your location :(")