技术支持 - 数据库解析示例代码

代码示例

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()