使用场景:
在没网的情况下使用python代码实现对ip地址进行查询国家和地市
代码实现:
需要安装 pip install geoip2 库
import geoip2.database
def get_location_by_ip(ip_address, db_path):
reader = geoip2.database.Reader(db_path)
try:
response = reader.city(ip_address)
city = response.city.name
country = response.country.name
# 你可以根据需要获取更多的信息,如省份、经纬度等
# ...
return city, country
except geoip2.errors.AddressNotFoundError:
return None, None # IP地址未找到
finally:
reader.close()
db_path = 'E:\personal\project_pro\ChatTTS\ChatTTS\GeoLite2-City.mmdb' # 替换为你的数据库文件路径
ip_address = '119.23.141.***' # 示例IP地址
city, country = get_location_by_ip(ip_address, db_path)
print(f"City: {city}, Country: {country}")