本机 IP 请求示例
每个示例调用相同的端点。建立连接的进程决定返回谁的 IP 地址。
使用支持原生 fetch 和 AbortSignal.timeout 的 JavaScript 模块或浏览器控制台。
const response = await fetch(
"https://api.ipquery.io/?format=json",
{ signal: AbortSignal.timeout(5000) }
);
if (!response.ok) {
const message = await response.text();
throw new Error("IPQuery " + response.status + ": " + message);
}
const data = await response.json();
console.log(JSON.stringify(data, null, 2));
在 shell 中使用 cURL 运行。HTTP 错误会以非零状态退出;诊断信息输出到 stderr。
curl --fail --silent --show-error --max-time 5 \
"https://api.ipquery.io/?format=json"
Python 3,仅使用标准库。超时适用于套接字操作。
import json
from urllib.request import urlopen
with urlopen("https://api.ipquery.io/?format=json", timeout=5) as response:
data = json.load(response)
print(json.dumps(data, indent=2))
Go,仅使用标准库。保存为 main.go 并运行 go run main.go。
package main
import (
"io"
"log"
"net/http"
"os"
"time"
)
func main() {
client := &http.Client{Timeout: 5 * time.Second}
response, err := client.Get("https://api.ipquery.io/?format=json")
if err != nil { log.Fatal(err) }
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
log.Fatalf("IPQuery %s", response.Status)
}
if _, err := io.Copy(os.Stdout, response.Body); err != nil {
log.Fatal(err)
}
}
这些示例使用五秒超时和各语言的标准 HTTP 工具。请在应用中处理故障,不要替换为空的 IP 记录。