准备工作:安装必备工具
首先,请确保你的Python环境中安装了requests库。
1pip install requests 2
第一步:查询自己的公网 IP 信息
1import requests 2import json 3 4# 向ipinfo.io发送请求,不带任何IP地址,它会默认查询你自己的IP 5url = "https://ipinfo.io/json" 6 7try: 8 response = requests.get(url) 9 response.raise_for_status() # 如果请求失败 (如状态码 4xx, 5xx), 会抛出异常 10 11 # 将返回的JSON格式数据解析为Python字典 12 data = response.json() 13 14 print("--- 你的IP信息详情 ---") 15 # 为了美观,使用json.dumps进行格式化输出 16 print(json.dumps(data, indent=4, ensure_ascii=False)) 17 18except requests.exceptions.RequestException as e: 19 print(f"请求失败: {e}") 20
运行后,你将看到类似这样的输出(信息会根据你的实际情况而变):
1{ 2 "ip": "xxx.xxx.xxx.xxx", 3 "hostname": "some.host.name", 4 "city": "xx", 5 "region": "xx", 6 "country": "CN", 7 "loc": "39.9042,116.4074", 8 "org": "xx", 9 "postal": "100000", 10 "timezone": "Asia/Shanghai", 11 "readme": "https://ipinfo.io/missingauth" 12} 13
第二步:查询任意指定的 IP 地址
我们可以查询任何一个我们想查的公网IP,比如谷歌的公共DNS服务器 8.8.8.8。
1import requests 2import json 3 4# 定义要查询的IP地址 5target_ip = "8.8.8.8" 6 7# 构造请求URL,将IP地址拼接到URL中 8url = f"https://ipinfo.io/{target_ip}/json" 9 10try: 11 response = requests.get(url) 12 response.raise_for_status() 13 14 data = response.json() 15 16 print(f"--- IP: {target_ip} 的信息详情 ---") 17 print(json.dumps(data, indent=4, ensure_ascii=False)) 18 19except requests.exceptions.RequestException as e: 20 print(f"请求失败: {e}") 21
输出将会是:
1{ 2 "ip": "8.8.8.8", 3 "hostname": "dns.google", 4 "city": "Mountain View", 5 "region": "California", 6 "country": "US", 7 "loc": "37.4056,-122.0775", 8 "org": "AS15169 Google LLC", 9 "postal": "94043", 10 "timezone": "America/Los_Angeles", 11 "readme": "https://ipinfo.io/missingauth", 12 "anycast": true 13} 14
第三步:自由封装成自己需要的内容显示库
示例
1import requests 2 3def get_ip_info(ip_address: str) -> dict | None: 4 """ 5 查询指定IP地址的详细信息。 6 7 :param ip_address: 要查询的IP地址字符串。 8 :return: 包含IP信息的字典,如果查询失败则返回None。 9 """ 10 url = f"https://ipinfo.io/{ip_address}/json" 11 try: 12 response = requests.get(url, timeout=5) # 增加超时设置 13 response.raise_for_status() 14 return response.json() 15 except requests.exceptions.RequestException as e: 16 print(f"查询IP {ip_address} 时出错: {e}") 17 return None 18 19# --- 使用我们封装好的函数 --- 20if __name__ == "__main__": 21 ip_list = ["8.8.8.8", "1.1.1.1", "114.114.114.114"] 22 23 for ip in ip_list: 24 info = get_ip_info(ip) 25 if info: 26 country = info.get('country', 'N/A') 27 city = info.get('city', 'N/A') 28 org = info.get('org', 'N/A') 29 print(f"IP: {ip:<15} | Location: {country}, {city} | Organization: {org}") 30
结语
点个赞,关注我获取更多实用 Python 技术干货!如果觉得有用,记得收藏本文!
《用 Python 揭秘 IP 地址背后的地理位置和信息》 是转载文章,点击查看原文。
