import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
public class MMDBParser {
// MMDB 文件目录
private static final String MMDB_DIR = "downloaded_files";
// MMDB 文件列表
private static final String[] MMDB_FILES = {
"ipv4-qx.mmdb",
"ipv4-cs.mmdb",
"ipv6-qx.mmdb",
"ipv6-cs.mmdb"
};
public static void main(String[] args) {
// 测试 IP 地址(可以替换为其他 IP)
String[] testIps = {
"8.8.8.8", // IPv4 示例(Google DNS)
"2001:4860:4860::8888" // IPv6 示例(Google DNS)
};
// 遍历 MMDB 文件
for (String mmdbFile : MMDB_FILES) {
File database = new File(MMDB_DIR, mmdbFile);
System.out.println("\n解析 MMDB 文件: " + mmdbFile);
try (DatabaseReader reader = new DatabaseReader.Builder(database).build()) {
// 遍历测试 IP 地址
for (String ip : testIps) {
try {
// 解析 IP 地址
InetAddress ipAddress = InetAddress.getByName(ip);
CityResponse response = reader.city(ipAddress);
// 获取地理信息
Country country = response.getCountry();
City city = response.getCity();
Location location = response.getLocation();
Postal postal = response.getPostal();
// 打印结果
System.out.println("IP 地址: " + ip);
System.out.println("国家: " + (country.getName() != null ? country.getName() : "未知"));
System.out.println("城市: " + (city.getName() != null ? city.getName() : "未知"));
System.out.println("邮编: " + (postal.getCode() != null ? postal.getCode() : "未知"));
System.out.println("经纬度: " + (location.getLatitude() != null ?
location.getLatitude() + "," + location.getLongitude() : "未知"));
System.out.println("------------------------");
} catch (GeoIp2Exception e) {
System.err.println("查询 IP " + ip + " 失败: " + e.getMessage());
}
}
} catch (IOException e) {
System.err.println("无法加载 MMDB 文件 " + mmdbFile + ": " + e.getMessage());
}
}
}
}
package main
import (
"fmt"
"log"
"net"
"path/filepath"
"github.com/oschwald/maxminddb-golang"
)
// MMDB 文件目录
const mmdbDir = "downloaded_files"
// MMDB 文件列表
var mmdbFiles = []string{
"ipv4-qx.mmdb",
"ipv4-cs.mmdb",
"ipv6-qx.mmdb",
"ipv6-cs.mmdb",
}
// 测试 IP 地址
var testIPs = []string{
"8.8.8.8", // IPv4 示例(Google DNS)
"2001:4860:4860::8888", // IPv6 示例(Google DNS)
}
// 定义地理信息结构体(根据 MMDB 文件的实际结构调整)
type GeoInfo struct {
Country struct {
Names map[string]string `maxminddb:"names"`
} `maxminddb:"country"`
City struct {
Names map[string]string `maxminddb:"names"`
} `maxminddb:"city"`
Location struct {
Latitude float64 `maxminddb:"latitude"`
Longitude float64 `maxminddb:"longitude"`
} `maxminddb:"location"`
Postal struct {
Code string `maxminddb:"code"`
} `maxminddb:"postal"`
}
func parseMMDB(filePath string, ipStr string) error {
// 打开 MMDB 文件
db, err := maxminddb.Open(filePath)
if err != nil {
return fmt.Errorf("无法加载 MMDB 文件 %s: %v", filePath, err)
}
defer db.Close()
// 解析 IP 地址
ip := net.ParseIP(ipStr)
if ip == nil {
return fmt.Errorf("无效的 IP 地址: %s", ipStr)
}
// 查询 IP 信息
var record GeoInfo
err = db.Lookup(ip, &record)
if err != nil {
return fmt.Errorf("查询 IP %s 失败: %v", ipStr, err)
}
// 打印结果
fmt.Printf("IP 地址: %s\n", ipStr)
fmt.Printf("国家: %s\n", record.Country.Names["en"])
fmt.Printf("城市: %s\n", record.City.Names["en"])
fmt.Printf("邮编: %s\n", record.Postal.Code)
if record.Location.Latitude != 0 && record.Location.Longitude != 0 {
fmt.Printf("经纬度: %f,%f\n", record.Location.Latitude, record.Location.Longitude)
} else {
fmt.Printf("经纬度: 未知\n")
}
fmt.Println("------------------------")
return nil
}
func main() {
for _, mmdbFile := range mmdbFiles {
filePath := filepath.Join(mmdbDir, mmdbFile)
fmt.Printf("\n解析 MMDB 文件: %s\n", mmdbFile)
for _, ip := range testIPs {
if err := parseMMDB(filePath, ip); err != nil {
log.Printf("处理 %s 失败: %v", ip, err)
}
}
}
}
<?php
require 'vendor/autoload.php'; // 如果使用 Composer
use GeoIp2\Database\Reader;
// MMDB 文件目录
$mmdbDir = 'downloaded_files';
// MMDB 文件列表
$mmdbFiles = [
'ipv4-qx.mmdb',
'ipv4-cs.mmdb',
'ipv6-qx.mmdb',
'ipv6-cs.mmdb'
];
// 测试 IP 地址
$testIps = [
'8.8.8.8', // IPv4 示例(Google DNS)
'2001:4860:4860::8888' // IPv6 示例(Google DNS)
];
foreach ($mmdbFiles as $mmdbFile) {
$filePath = $mmdbDir . DIRECTORY_SEPARATOR . $mmdbFile;
echo "\n解析 MMDB 文件: $mmdbFile\n";
try {
// 加载 MMDB 文件
$reader = new Reader($filePath);
foreach ($testIps as $ip) {
try {
// 查询 IP 信息(假设是 City 数据库)
$record = $reader->city($ip);
// 提取地理信息
$country = $record->country->name ?? '未知';
$city = $record->city->name ?? '未知';
$postal = $record->postal->code ?? '未知';
$latitude = $record->location->latitude ?? '未知';
$longitude = $record->location->longitude ?? '未知';
// 打印结果
echo "IP 地址: $ip\n";
echo "国家: $country\n";
echo "城市: $city\n";
echo "邮编: $postal\n";
echo "经纬度: " . ($latitude !== '未知' ? "$latitude,$longitude" : '未知') . "\n";
echo "------------------------\n";
} catch (\GeoIp2\Exception\AddressNotFoundException $e) {
echo "IP $ip 未在数据库中找到\n";
echo "------------------------\n";
} catch (\Exception $e) {
echo "查询 IP $ip 失败: " . $e->getMessage() . "\n";
echo "------------------------\n";
}
}
// 关闭 Reader
$reader = null;
} catch (\MaxMind\Db\Reader\InvalidDatabaseException $e) {
echo "无法加载 MMDB 文件 $mmdbFile: " . $e->getMessage() . "\n";
} catch (\Exception $e) {
echo "处理 MMDB 文件 $mmdbFile 失败: " . $e->getMessage() . "\n";
}
}
?>
import os
import geoip2.database
from geoip2.errors import AddressNotFoundError
# MMDB 文件目录
MMDB_DIR = 'downloaded_files'
# MMDB 文件列表
MMDB_FILES = [
'ipv4-qx.mmdb',
'ipv4-cs.mmdb',
'ipv6-qx.mmdb',
'ipv6-cs.mmdb'
]
# 测试 IP 地址
TEST_IPS = [
'8.8.8.8', # IPv4 示例(Google DNS)
'2001:4860:4860::8888' # IPv6 示例(Google DNS)
]
def parse_mmdb(file_path, ip):
try:
# 加载 MMDB 文件
with geoip2.database.Reader(file_path) as reader:
# 查询 IP 信息(假设是 City 数据库)
response = reader.city(ip)
# 提取地理信息
country = response.country.name if response.country.name else '未知'
city = response.city.name if response.city.name else '未知'
postal = response.postal.code if response.postal.code else '未知'
latitude = response.location.latitude if response.location.latitude else '未知'
longitude = response.location.longitude if response.location.longitude else '未知'
# 打印结果
print(f'IP 地址: {ip}')
print(f'国家: {country}')
print(f'城市: {city}')
print(f'邮编: {postal}')
print(f'经纬度: {latitude},{longitude}' if latitude != '未知' else '经纬度: 未知')
print('------------------------')
except AddressNotFoundError:
print(f'IP {ip} 未在数据库中找到')
print('------------------------')
except Exception as e:
print(f'查询 IP {ip} 失败: {str(e)}')
print('------------------------')
def main():
for mmdb_file in MMDB_FILES:
file_path = os.path.join(MMDB_DIR, mmdb_file)
print(f'\n解析 MMDB 文件: {mmdb_file}')
if not os.path.exists(file_path):
print(f'文件 {mmdb_file} 不存在')
continue
for ip in TEST_IPS:
parse_mmdb(file_path, ip)
if __name__ == '__main__':
main()
#!/bin/bash
# MMDB 文件目录
MMDB_DIR="downloaded_files"
# MMDB 文件列表
MMDB_FILES=(
"ipv4-qx.mmdb"
"ipv4-cs.mmdb"
"ipv6-qx.mmdb"
"ipv6-cs.mmdb"
)
# 测试 IP 地址
TEST_IPS=(
"8.8.8.8" # IPv4 示例(Google DNS)
"2001:4860:4860::8888" # IPv6 示例(Google DNS)
)
# 函数:解析 MMDB 文件并查询 IP
parse_mmdb() {
local mmdb_file="$1"
local ip="$2"
local file_path="$MMDB_DIR/$mmdb_file"
# 检查 MMDB 文件是否存在
if [ ! -f "$file_path" ]; then
echo "文件 $mmdb_file 不存在"
echo "------------------------"
return 1
fi
echo "IP 地址: $ip"
# 查询国家
country=$(mmdblookup --file "$file_path" --ip "$ip" country names en 2>/dev/null | grep -o '"[^"]*"' | tr -d '"')
echo "国家: ${country:-未知}"
# 查询城市
city=$(mmdblookup --file "$file_path" --ip "$ip" city names en 2>/dev/null | grep -o '"[^"]*"' | tr -d '"')
echo "城市: ${city:-未知}"
# 查询邮编
postal=$(mmdblookup --file "$file_path" --ip "$ip" postal code 2>/dev/null | grep -o '"[^"]*"' | tr -d '"')
echo "邮编: ${postal:-未知}"
# 查询经纬度
latitude=$(mmdblookup --file "$file_path" --ip "$ip" location latitude 2>/dev/null | grep -o '[0-9.-]\+')
longitude=$(mmdblookup --file "$file_path" --ip "$ip" location longitude 2>/dev/null | grep -o '[0-9.-]\+')
if [ -n "$latitude" ] && [ -n "$longitude" ]; then
echo "经纬度: $latitude,$longitude"
else
echo "经纬度: 未知"
fi
echo "------------------------"
}
# 主循环
for mmdb_file in "${MMDB_FILES[@]}"; do
echo -e "\n解析 MMDB 文件: $mmdb_file"
for ip in "${TEST_IPS[@]}"; do
parse_mmdb "$mmdb_file" "$ip"
done
done