根据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)
相关推荐
承渊政道36 分钟前
Linux网络学习【Reactor反应堆模式】
linux·网络·学习·ubuntu·reactor
爱和冰阔落5 小时前
【Linux网络】TCP 服务器如何并发处理多个客户端?从 fork、僵尸进程到双重 fork
linux·运维·服务器·网络
严肃小白兔6 小时前
Cloudflare 更新 API Token 管理:从最小权限到自动化凭据安全
网络·安全·自动化
Linux-lucky18 小时前
45-Linux学习之旅之防火墙与WEB加固
linux·前端·网络·学习·ubuntu
博客zhu虎康1 天前
实现局域网P2P通信:内网发送消息
网络·网络协议·p2p
吴声子夜歌1 天前
Kubernetes权威指南——网络原理(一)
网络·容器·kubernetes
陈希1231 天前
Linux 服务器性能排查手册(2026):CPU、内存、磁盘IO、网络四大瓶颈定位
linux·服务器·网络
国科安芯1 天前
从遥控到自治:ASP4644S2B支撑星载电源健康管理与容错配电
网络·单片机·嵌入式硬件·安全·dcdc·低轨卫星·商业航天
|_⊙1 天前
网络层协议 IP
服务器·网络·tcp/ip
无言听风雨丶1 天前
Kubernetes Service Mesh 与 mTLS 实战:从网络可达走向零信任服务通信
网络·kubernetes·service_mesh