获取我的 IP API
获取您当前的公网 IP 地址(IPv4 和 IPv6)
概述
获取我的 IP API 提供了一种简单的方式来获取您当前的公网 IP 地址。它支持 IPv4 和 IPv6 地址,并可以检测您网络的 IP 版本优先级。
接口地址
仅 IPv4
GET https://4.ipconfig.com/
仅 IPv6
GET https://6.ipconfig.com/
自动检测(包含优先级信息)
GET https://test.ipconfig.com/api/ip/myip
功能特性
- 免费服务:无需 API 密钥
- IPv4 和 IPv6 支持:同时获取 IPv4 和 IPv6 地址
- 网络优先级检测:确定您的网络是优先使用 IPv4 还是 IPv6
- 快速响应:通过全球 CDN 优化速度
- 无速率限制:基础使用无限制请求
使用示例
# 获取 IPv4 地址
curl https://4.ipconfig.com/
# 获取 IPv6 地址
curl https://6.ipconfig.com/
# 获取 IP 并检测优先级
curl https://test.ipconfig.com/api/ip/myip
// 使用 fetch API
async function getMyIP() {
try {
// 获取 IPv4
const ipv4Response = await fetch('https://4.ipconfig.com/');
const ipv4 = await ipv4Response.text();
// 获取 IPv6
const ipv6Response = await fetch('https://6.ipconfig.com/');
const ipv6 = await ipv6Response.text();
// 获取优先级信息
const testResponse = await fetch('https://test.ipconfig.com/api/ip/myip');
const testData = await testResponse.json();
return {
ipv4: ipv4.trim(),
ipv6: ipv6.trim(),
priority: testData.IPVersion || 'IPv4'
};
} catch (error) {
console.error('获取 IP 失败:', error);
return null;
}
}
// 使用方法
getMyIP().then(result => {
if (result) {
console.log('IPv4:', result.ipv4);
console.log('IPv6:', result.ipv6);
console.log('网络优先级:', result.priority);
}
});
import requests
import json
def get_my_ip():
"""获取当前公网 IP 地址和网络优先级"""
result = {
'ipv4': None,
'ipv6': None,
'priority': 'IPv4'
}
try:
# 获取 IPv4 地址
ipv4_response = requests.get('https://4.ipconfig.com/', timeout=5)
if ipv4_response.ok:
result['ipv4'] = ipv4_response.text.strip()
except:
pass
try:
# 获取 IPv6 地址
ipv6_response = requests.get('https://6.ipconfig.com/', timeout=5)
if ipv6_response.ok:
result['ipv6'] = ipv6_response.text.strip()
except:
pass
try:
# 获取网络优先级
test_response = requests.get('https://test.ipconfig.com/api/ip/myip', timeout=5)
if test_response.ok:
test_data = test_response.json()
result['priority'] = test_data.get('IPVersion', 'IPv4')
except:
pass
return result
# 使用示例
if __name__ == "__main__":
ip_info = get_my_ip()
print(f"IPv4: {ip_info['ipv4'] or '不可用'}")
print(f"IPv6: {ip_info['ipv6'] or '不可用'}")
print(f"网络优先级: {ip_info['priority']}")
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
type IPInfo struct {
IPv4 string `json:"ipv4"`
IPv6 string `json:"ipv6"`
Priority string `json:"priority"`
}
type TestResponse struct {
IPVersion string `json:"IPVersion"`
}
func getMyIP() (*IPInfo, error) {
client := &http.Client{Timeout: 5 * time.Second}
result := &IPInfo{Priority: "IPv4"}
// 获取 IPv4
if resp, err := client.Get("https://4.ipconfig.com/"); err == nil {
defer resp.Body.Close()
if body, err := io.ReadAll(resp.Body); err == nil {
result.IPv4 = strings.TrimSpace(string(body))
}
}
// 获取 IPv6
if resp, err := client.Get("https://6.ipconfig.com/"); err == nil {
defer resp.Body.Close()
if body, err := io.ReadAll(resp.Body); err == nil {
result.IPv6 = strings.TrimSpace(string(body))
}
}
// 获取优先级
if resp, err := client.Get("https://test.ipconfig.com/api/ip/myip"); err == nil {
defer resp.Body.Close()
if body, err := io.ReadAll(resp.Body); err == nil {
var testResp TestResponse
if json.Unmarshal(body, &testResp) == nil {
result.Priority = testResp.IPVersion
}
}
}
return result, nil
}
func main() {
ipInfo, err := getMyIP()
if err != nil {
fmt.Printf("错误: %v\n", err)
return
}
fmt.Printf("IPv4: %s\n", getValueOrDefault(ipInfo.IPv4, "不可用"))
fmt.Printf("IPv6: %s\n", getValueOrDefault(ipInfo.IPv6, "不可用"))
fmt.Printf("网络优先级: %s\n", ipInfo.Priority)
}
func getValueOrDefault(value, defaultValue string) string {
if value == "" {
return defaultValue
}
return value
}
<?php
function getMyIP() {
$result = [
'ipv4' => null,
'ipv6' => null,
'priority' => 'IPv4'
];
// 获取 IPv4 地址
try {
$ipv4 = @file_get_contents('https://4.ipconfig.com/');
if ($ipv4 !== false) {
$result['ipv4'] = trim($ipv4);
}
} catch (Exception $e) {
// 忽略错误
}
// 获取 IPv6 地址
try {
$ipv6 = @file_get_contents('https://6.ipconfig.com/');
if ($ipv6 !== false) {
$result['ipv6'] = trim($ipv6);
}
} catch (Exception $e) {
// 忽略错误
}
// 获取网络优先级
try {
$testResponse = @file_get_contents('https://test.ipconfig.com/api/ip/myip');
if ($testResponse !== false) {
$testData = json_decode($testResponse, true);
if (isset($testData['IPVersion'])) {
$result['priority'] = $testData['IPVersion'];
}
}
} catch (Exception $e) {
// 忽略错误
}
return $result;
}
// 使用示例
$ipInfo = getMyIP();
echo "IPv4: " . ($ipInfo['ipv4'] ?: '不可用') . "\n";
echo "IPv6: " . ($ipInfo['ipv6'] ?: '不可用') . "\n";
echo "网络优先级: " . $ipInfo['priority'] . "\n";
?>
响应格式
简单文本响应(4.ipconfig.com, 6.ipconfig.com)
203.0.113.1
JSON 响应(test.ipconfig.com/api/ip/myip)
{
"result": true,
"code": "querySuccess",
"message": "Query Success",
"IP": "150.171.28.10",
"IPVersion": "IPv4"
}
{
"result": true,
"code": "querySuccess",
"message": "Query Success",
"IP": "2620:1ec:33:1::10",
"IPVersion": "IPv6"
}
错误处理
该服务设计为高可用性,但您应该始终实现适当的错误处理:
async function getIPWithErrorHandling() {
try {
const response = await fetch('https://4.ipconfig.com/', {
signal: AbortSignal.timeout(5000) // 5 秒超时
});
if (!response.ok) {
throw new Error(`HTTP 错误! 状态: ${response.status}`);
}
return await response.text();
} catch (error) {
if (error.name === 'AbortError') {
console.error('请求超时');
} else {
console.error('网络错误:', error.message);
}
return null;
}
}
使用场景
- 网络诊断:检查您当前的公网 IP
- 地理位置服务:确定用户的大致位置
- 安全应用:监控 IP 变化
- 开发测试:使用不同 IP 场景测试应用
- VPN 检测:验证 VPN 连接状态
最佳实践
- 实现超时:始终设置合理的超时时间(3-5 秒)
- 优雅处理错误:网络请求可能失败
- 缓存结果:通过短期缓存 IP 避免不必要的请求
- 使用适当的端点:根据需要选择 IPv4、IPv6 或自动检测
- 尊重速率限制:虽然没有严格限制,但避免过度请求
相关 API
- IP 归属地查询 API - 获取任何 IP 的详细位置信息
- Ping 测试 API - 测试到全球各地的网络连接