发布于 更新于
AI总结: 本文介绍了ip2region及其相关数据库的信息,包括ip2region-xdb的大小和数据来源,以及MaxMind的GeoLite2数据库更新频率和使用示例。该示例展示了如何使用geoip2库查询IP地址的国家信息。
优化建议:
1. 在函数get_ip_info中,增加对输入IP地址格式的验证,以确保输入有效性。
2. 考虑将数据库路径作为参数传递时,提供默认值的同时,允许用户自定义路径。
3. 在异常处理部分,建议增加日志记录功能,以便后续分析失败的查询。
4. 提供更多的使用示例,展示如何获取城市和ASN信息,增强实用性。
ip2region-xdb 58M
数据来自IP-API
GeoLite2-Database 每3天更新
MaxMind's GeoLite2 Country, City, and ASN databases in csv and mmdb.
maxmind-geoip 每月12号更新
geoip2-mirror 每周二,五更新
import geoip2.database
def get_ip_info(ip_address, db_path="GeoLite2-Country.mmdb"):
try:
with geoip2.database.Reader(db_path) as reader:
response = reader.country(ip_address)
return response.country.names.get('zh-CN', response.country.name)
except Exception as e:
print(f"GeoIP lookup failed for {ip_address}: {e}")
return ''
# 使用示例
ip_address = "8.8.8.8"
country = get_ip_info(ip_address)
print(f"Country: {country}")