1. 安装 geoip2

首先,确保你已经安装了 geoip2 库。如果没有安装,可以通过以下命令安装:

bash pip install geoip2


2. 下载 GeoIP2 数据库

geoip2 需要依赖 MaxMind 的 GeoIP2 数据库文件(通常是 .mmdb 文件)。你可以从 MaxMind 官网下载免费的 GeoLite2 数据库,或者购买更精确的 GeoIP2 数据库。


3. 使用 geoip2 查询 IP 地址所在地

以下是一个完整的 Python 示例代码,展示如何使用 geoip2 查询 IP 地址的所在地信息。

```python import geoip2.database

加载 GeoIP2 数据库文件

reader = geoip2.database.Reader('GeoLite2-City.mmdb')

def getiplocation(ipaddress): try: # 查询 IP 地址 response = reader.city(ipaddress)

    # 提取地理位置信息
    country = response.country.name
    province = response.subdivisions.most_specific.name  # 省份或州
    city = response.city.name
    postal_code = response.postal.code
    latitude = response.location.latitude
    longitude = response.location.longitude

    return {
        "IP": ip_address,
        "Country": country,
        "Province": province,
        "City": city,
        "Postal Code": postal_code,
        "Latitude": latitude,
        "Longitude": longitude
    }
except Exception as e:
    return {"error": str(e)}

示例 IP 地址

ipaddress = "8.8.8.8" # Google 的公共 DNS IP location = getiplocation(ipaddress)

打印结果

if "error" in location: print(f"Error: {location['error']}") else: for key, value in location.items(): print(f"{key}: {value}")

关闭数据库连接

reader.close() ```


4. 代码说明


5. 示例输出

对于 IP 地址 8.8.8.8,输出可能如下:

IP: 8.8.8.8 Country: United States Province: California City: Mountain View Postal Code: 94043 Latitude: 37.4056 Longitude: -122.0775


6. 注意事项


通过以上方法,你可以轻松使用 geoip2 查询 IP 地址的所在地信息。如果有更多需求(如批量查询),可以将代码封装成函数或类。