根据IP查询城市ID和名字

根据IP查询城市ID和名字

python 复制代码
import json
import time
import geoip2.database
import requests
from loguru import logger
#创建GeoIP对象,并指定数据库路径
reader = geoip2.database.Reader(r'D:\thb\code\python-trial\pythonProject\data\GeoLite2-City.mmdb')

#web addr: https://ip.taobao.com/ipSearch
#淘宝 IP 库提供的 Rest 风格接口:10qps
def query_china_ip_location(ipaddress: str):
    req_params={
        "ip": ipaddress,
        "accessKey":"alibaba-inc"
    }
    cityid=None
    cityname=None
    rsp=requests.post(url="http://ip.taobao.com/outGetIpInfo",data=req_params)
    '''
    {
    "data": {
        "area": "",
        "country": "中国",
        "isp_id": "100017",
        "queryIp": "118.251.69.6",
        "city": "株洲",
        "ip": "118.251.69.6",
        "isp": "电信",
        "county": "",
        "region_id": "430000",
        "area_id": "",
        "county_id": null,
        "region": "湖南",
        "country_id": "CN",
        "city_id": "430200"
    },
    "msg": "query success",
    "code": 0
   }
    '''
    if rsp.status_code == 200:
        logger.info("result:{}",rsp.text)
        data_dict=json.loads(rsp.text)
        if data_dict.get("data") is not None:
           cityid = data_dict.get("data").get("city_id")
           cityname = data_dict.get("data").get("city")
    return cityid,cityname

#基于maxmind的IP查询,适合于国外IP
def query_ip_location(ip):
    try:
        # 查询IP归宿地
        response = reader.city(ip)
        # 提取国家名称
        country = response.country.name
        # 提取城市信息,如果存在的话
        city = response.city.name
        if city:
            return f"{country} | {city}"
        else:
            return country
    except geoip2.errors.AddressNotFoundError:
        return "IP地址未找到"

if __name__ == "__main__":
    #测试查询
    #ip_location = query_ip_location('128.101.101.101')
    #print(ip_location)
    ip_addrs=["118.124.102.247","183.222.178.180","117.183.162.183","118.251.69.6"]
    for ip_address in ip_addrs:
        time.sleep(1)
        cityid,cityname=query_china_ip_location(ip_address)
        logger.info("cityid:{},cityname:{}",cityid,cityname)
相关推荐
blasit15 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
YuMiao20 小时前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
Jony_4 天前
高可用移动网络连接
网络协议
chilix4 天前
Linux 跨网段路由转发配置
网络协议
DianSan_ERP5 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet
呉師傅6 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
gihigo19986 天前
基于TCP协议实现视频采集与通信
网络协议·tcp/ip·音视频
2501_946205526 天前
晶圆机器人双臂怎么选型?适配2-12寸晶圆的末端效应器有哪些?
服务器·网络·机器人
linux kernel6 天前
第七部分:高级IO
服务器·网络
数字护盾(和中)6 天前
BAS+ATT&CK:企业主动防御的黄金组合
服务器·网络·数据库