用 Python 揭秘 IP 地址背后的地理位置和信息

准备工作:安装必备工具

首先,请确保你的Python环境中安装了requests库。

bash 复制代码
pip install requests

第一步:查询自己的公网 IP 信息

python 复制代码
import requests
import json

# 向ipinfo.io发送请求,不带任何IP地址,它会默认查询你自己的IP
url = "https://ipinfo.io/json"

try:
    response = requests.get(url)
    response.raise_for_status() # 如果请求失败 (如状态码 4xx, 5xx), 会抛出异常

    # 将返回的JSON格式数据解析为Python字典
    data = response.json()

    print("--- 你的IP信息详情 ---")
    # 为了美观,使用json.dumps进行格式化输出
    print(json.dumps(data, indent=4, ensure_ascii=False))

except requests.exceptions.RequestException as e:
    print(f"请求失败: {e}")

运行后,你将看到类似这样的输出(信息会根据你的实际情况而变):

json 复制代码
{
    "ip": "xxx.xxx.xxx.xxx",
    "hostname": "some.host.name",
    "city": "xx",
    "region": "xx",
    "country": "CN",
    "loc": "39.9042,116.4074",
    "org": "xx",
    "postal": "100000",
    "timezone": "Asia/Shanghai",
    "readme": "https://ipinfo.io/missingauth"
}

第二步:查询任意指定的 IP 地址

我们可以查询任何一个我们想查的公网IP,比如谷歌的公共DNS服务器 8.8.8.8

python 复制代码
import requests
import json

# 定义要查询的IP地址
target_ip = "8.8.8.8"

# 构造请求URL,将IP地址拼接到URL中
url = f"https://ipinfo.io/{target_ip}/json"

try:
    response = requests.get(url)
    response.raise_for_status()

    data = response.json()

    print(f"--- IP: {target_ip} 的信息详情 ---")
    print(json.dumps(data, indent=4, ensure_ascii=False))

except requests.exceptions.RequestException as e:
    print(f"请求失败: {e}")

输出将会是:

json 复制代码
{
    "ip": "8.8.8.8",
    "hostname": "dns.google",
    "city": "Mountain View",
    "region": "California",
    "country": "US",
    "loc": "37.4056,-122.0775",
    "org": "AS15169 Google LLC",
    "postal": "94043",
    "timezone": "America/Los_Angeles",
    "readme": "https://ipinfo.io/missingauth",
    "anycast": true
}

第三步:自由封装成自己需要的内容显示库

示例

python 复制代码
import requests

def get_ip_info(ip_address: str) -> dict | None:
    """
    查询指定IP地址的详细信息。
    
    :param ip_address: 要查询的IP地址字符串。
    :return: 包含IP信息的字典,如果查询失败则返回None。
    """
    url = f"https://ipinfo.io/{ip_address}/json"
    try:
        response = requests.get(url, timeout=5) # 增加超时设置
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"查询IP {ip_address} 时出错: {e}")
        return None

# --- 使用我们封装好的函数 ---
if __name__ == "__main__":
    ip_list = ["8.8.8.8", "1.1.1.1", "114.114.114.114"]
    
    for ip in ip_list:
        info = get_ip_info(ip)
        if info:
            country = info.get('country', 'N/A')
            city = info.get('city', 'N/A')
            org = info.get('org', 'N/A')
            print(f"IP: {ip:<15} | Location: {country}, {city} | Organization: {org}")

结语

点个赞,关注我获取更多实用 Python 技术干货!如果觉得有用,记得收藏本文!

相关推荐
大宝剑1703 小时前
python环境安装
开发语言·python
前端开发爱好者3 小时前
尤雨溪官宣:"新玩具" 比 Prettier 快 45 倍!
前端·javascript·vue.js
why技术3 小时前
从18w到1600w播放量,我的一点思考。
java·前端·后端
欧阳呀3 小时前
Vue+element ui导入组件封装——超级优雅版
前端·javascript·vue.js·elementui
清风徐来QCQ3 小时前
css总结
前端
Element_南笙3 小时前
吴恩达新课程:Agentic AI(笔记2)
数据库·人工智能·笔记·python·深度学习·ui·自然语言处理
倔强青铜三4 小时前
苦练Python第69天:subprocess模块从入门到上瘾,手把手教你驯服系统命令!
人工智能·python·面试
倔强青铜三4 小时前
苦练 Python 第 68 天:并发狂飙!concurrent 模块让你 CPU 原地起飞
人工智能·python·面试
星期天要睡觉4 小时前
深度学习——循环神经网络(RNN)实战项目:基于PyTorch的文本情感分析
人工智能·python·rnn·深度学习·神经网络