ZVVQ代理分享网

MaxMind GeoIP 演示指南

作者:zvvq博客网

MaxMind GeoIP 演示指南

全面了解如何使用 MaxMind 的 GeoIP 数据库和 Web 服务进行地理位置查询

本地数据库

下载并使用 GeoLite2 数据库,支持多种编程语言查询

Web 服务

通过 RESTful API 接口查询 IP 地理位置信息

集成应用

将 GeoIP 集成到 Nginx、Node.js 等环境中实现高级功能

1. GeoIP 数据库的本地演示

下载与更新

  • 访问 MaxMind 官网 注册账号后,可下载数据库文件
  • 使用 geoipupdate 工具定时更新数据库(如通过 crontab 脚本自动化更新)

本地查询示例

Python 示例

import geoip2.database

reader = geoip2.database.Reader('GeoLite2-City.mmdb')
response = reader.get('223.192.2.165')
print(f"国家或地区: {response.country.name}, 城市: {response.city.name}")

PHP 示例

<?php
$gi = geoip_open("GeoLiteCity.dat", GEOIP_STANDARD);
$country = geoip_record_by_name($gi, "223.192.2.165");
geoip_close($gi);
echo "国家: " . $country['country']['name'] . ", 城市: " . $country['city'] . "<br>";
?>

Node.js 示例

const MaxMind = require('maxmind');
const lookup = new MaxMind.Reader('path/to/GeoLite2-City.mmdb');

const ip = '223.192.2.165';
const result = lookup.get(ip);
console.log(`国家: ${result.country.name}, 城市: ${result.city}`);
lookup.close();

2. GeoIP Web 服务的在线演示

API 端点

国家查询
https://geoip.maxmind.com/geoip/v2.1/country/{ip_address}
城市+服务
https://geoip.maxmind.com/geoip/v2.1/city/{ip_address}
洞察服务
https://geoip.maxmind.com/geoip/v2.1/insights/{ip_address}

返回 JSON 格式的地理位置信息,包括国家、城市、经纬度等详细数据。

沙盒环境测试

MaxMind 提供沙盒环境(Sandbox)用于测试,但数据仅限测试用途,不保证准确性。

curl "https://sandbox.maxmind.com/geoip/v2.1/country/8.8.8.8?license_key=YOUR_LICENSE_KEY"

3. 可视化与集成演示

Nginx 配置

通过 Nginx 模块(如 ngx_http_geoip_module)直接解析 IP 地理位置,实现个性化路由或访问控制。

geoip_country /usr/share/GeoIP/GeoIP.dat;

server {
    listen 80;
    server_name example.com;

    location / {
        if ($geoip_country_code = CN) {
            return 301 https://cn.example.com$request_uri;
        }
        if ($geoip_country_code = US) {
            return 301 https://us.example.com$request_uri;
        }
        # 默认处理
        proxy_pass http://backend;
    }
}

开源库集成

MaxMind 提供多种语言的 SDK(如 Java、Python、Go),支持快速开发。

// Python 示例
from flask import Flask
import geoip2.database

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

@app.route('/ip/')
def get_ip_location(ip_address):
    try:
        response = reader.get(ip_address)
        return {
            'country': response.country.name,
            'city': response.city.name,
            'latitude': response.location.latitude,
            'longitude': response.location.longitude
        }
    except Exception as e:
        return str(e), 500

if __name__ == '__main__':
    app.run(debug=True)

4. 注意事项

数据精度

GeoIP 的经纬度坐标不精确,不可用于识别具体街道或家庭地址。

免费限制

旧版 GeoIP Legacy 产品已停止即时访问,需升级至 GeoIP2。

商业用途

生产环境需购买许可证,沙盒数据仅限测试。

5. GeoIP 查询结果可视化

IP 地理位置分布

查询结果示例

IP 地址
223.192.2.165
国家
中国
城市
北京
经纬度
39.9042° N, 116.4074° E
时区
Asia/Shanghai
ISP
China Mobile