通过API接口解析请求头或调用第三方服务获取客户端IP,注意代理服务器可能影响
通过API获取IP地址的详细指南
常见IP获取API列表
以下是常用的公共IP地址查询API服务:
API名称 | 地址 | 特点 |
---|---|---|
ipify | https://api.ipify.org?format=json | 极简设计,支持JSON/text格式,无API限制 |
ipinfo | https://ipinfo.io/json | 提供地理位置信息,免费版每日5000次请求 |
ip-api | https://ipapi.co/json/ | 包含ISP信息,免费版每日45次请求需注册 |
ipapi | https://httpbin.org/ip | 仅返回IP,无地理位置信息,无请求限制 |
自建服务 | 需自行部署 | 可完全自定义,适合对数据隐私有高要求的场景 |
使用API获取IP的通用步骤
选择API服务
根据需求选择:
- 仅需IP:
ipify
或httpbin
- 需地理位置:
ipinfo
或ip-api
- 高隐私要求:自建服务
发送HTTP请求
import requests # 示例:使用ipify获取IP response = requests.get("https://api.ipify.org?format=json") data = response.json() print("Your IP is:", data["ip"])
解析响应数据
字段名 | 说明 | 常见数据类型 |
---|---|---|
ip | 公网IPv4地址 | 字符串(如2.3.4 ) |
hostname | 反向解析域名(部分API) | 字符串(如example.com ) |
city | 所在城市(部分API) | 字符串 |
region | 所在地区(部分API) | 字符串 |
org | 网络提供商(部分API) | 字符串 |
代码实现示例
Python实现(带错误处理)
import requests def get_public_ip(): url = "https://api.ipify.org?format=json" # 可替换为其他API try: response = requests.get(url, timeout=5) response.raise_for_status() # 检查HTTP状态码 data = response.json() return data["ip"] except requests.exceptions.RequestException as e: return f"Error: {e}" if __name__ == "__main__": print("Public IP:", get_public_ip())
关键参数说明
参数 | 作用 |
---|---|
timeout | 请求超时时间(秒) |
format | 响应格式(json /text ) |
fields | 指定返回字段(部分API支持) |
相关问题与解答
Q1:如何判断获取的IP是公网IP还是内网IP?
A:
公网IP范围:
0.0.0~49.255.255.255
0.0.0~139.255.255.255
172.0.0~255.255.255.255
(实际需排除私有段)
私有IP范围:
0.0.0~10.255.255.255
16.0.0~172.31.255.255
168.0.0~192.168.255.255
判断方法:
def is_public_ip(ip): private_ranges = [ "10.0.0.0/8", # 10.0.0.0 10.255.255.255 "172.16.0.0/12", # 172.16.0.0 172.31.255.255 "192.168.0.0/16" # 192.168.0.0 192.168.255.255 ] import ipaddress return not any(ipaddress.ip_address(ip) in ipaddress.ip_network(rng) for rng in private_ranges)
Q2:如果API请求失败怎么办?
A:
- 检查网络连接:确保设备能访问互联网
- 更换API服务:尝试其他公共API(如
ipapi
通常更稳定) - 增加重试机制:
import time
def get_ip_with_retry(max_retries=3):
for attempt in range(max_retries):
try:
return get_public_ip()
except Exception:
if attempt < max_retries 1:
time.sleep(2) # 等待2秒后重试
else:
return “Failed to fetch
以上内容就是解答有关“api 获取ip”的详细内容了,我相信这篇文章可以为您解决一些疑惑,有任何问题欢迎留言反馈,谢谢阅读。
【版权声明】:本站所有内容均来自网络,若无意侵犯到您的权利,请及时与我们联系将尽快删除相关内容!
发表回复