Ping 测试 API
测试到全球各地的网络连接性和延迟
概述
Ping 测试 API 允许您从多个全球位置测试到任何主机名或 IP 地址的网络连接性和延迟。获取详细的 ping 统计信息,包括丢包率、响应时间和网络路径信息。
接口地址
POST https://ipconfig.com/api/ping
身份验证
此 API 需要使用 API 密钥进行身份验证。在请求头中包含您的 API 密钥:
Authorization: Bearer YOUR_API_KEY
请求格式
请求头
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY
请求参数
参数 | 类型 | 必需 | 描述 |
---|---|---|---|
host | string | 是 | 要 ping 的目标主机名或 IP 地址 |
lang | string | 否 | 响应语言(en 或 zh )。默认:en |
ipVersion | string | 否 | IP 版本(ipv4 或 ipv6 )。默认:ipv4 |
areas | array | 否 | 测试位置。使用 ["all"] 测试所有位置或指定具体区域 |
count | number | 否 | 发送的 ping 包数量(1-10)。默认:4 |
请求示例
{
"host": "google.com",
"lang": "zh",
"ipVersion": "ipv4",
"areas": ["beijing", "tokyo", "california", "london"],
"count": 4
}
可用测试位置
亚太地区
beijing
- 北京,中国nanjing
- 南京,中国chengdu
- 成都,中国guangzhou
- 广州,中国hongkong
- 香港taiwan
- 台湾singapore
- 新加坡tokyo
- 东京,日本seoul
- 首尔,韩国mumbai
- 孟买,印度sydney
- 悉尼,澳大利亚
欧洲和中东
doha
- 多哈,卡塔尔frankfurt
- 法兰克福,德国london
- 伦敦,英国moscow
- 莫斯科,俄罗斯johannesburg
- 约翰内斯堡,南非
美洲
california
- 加利福尼亚,美国virginia
- 弗吉尼亚,美国dallas
- 达拉斯,美国chicago
- 芝加哥,美国seattle
- 西雅图,美国miami
- 迈阿密,美国newark
- 纽瓦克,美国saopaulo
- 圣保罗,巴西
使用示例
# 设置您的 API 密钥
export IPCONFIG_API_KEY='your-api-key-here'
# 测试特定位置
curl -H "Content-Type: application/json" \
-H "Authorization: Bearer $IPCONFIG_API_KEY" \
"https://ipconfig.com/api/ping" \
-d '{
"host": "google.com",
"lang": "zh",
"ipVersion": "ipv4",
"areas": ["beijing", "tokyo", "california"],
"count": 4
}'
# 测试所有位置
curl -H "Content-Type: application/json" \
-H "Authorization: Bearer $IPCONFIG_API_KEY" \
"https://ipconfig.com/api/ping" \
-d '{
"host": "example.com",
"lang": "zh",
"ipVersion": "ipv4",
"areas": ["all"],
"count": 2
}'
async function pingTest(host, options = {}) {
const apiKey = process.env.IPCONFIG_API_KEY;
if (!apiKey) {
throw new Error('API 密钥未配置');
}
const {
lang = 'zh',
ipVersion = 'ipv4',
areas = ['all'],
count = 4
} = options;
try {
const response = await fetch('https://ipconfig.com/api/ping', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
host,
lang,
ipVersion,
areas,
count
})
});
if (!response.ok) {
throw new Error(`HTTP 错误! 状态: ${response.status}`);
}
const data = await response.json();
if (data.success) {
return data.data;
} else {
throw new Error(data.error || '未知 API 错误');
}
} catch (error) {
console.error('Ping 测试失败:', error);
throw error;
}
}
// 使用示例
pingTest('google.com', {
areas: ['beijing', 'tokyo', 'california'],
count: 4
})
.then(result => {
console.log(`${result.pingHost} 的 Ping 测试结果:`);
console.log(`成功率: ${result.successNodes}/${result.totalNodes}`);
result.pingResultDetail.forEach(detail => {
if (detail.result && detail.pingResult) {
const location = detail.pingServerArea || detail.pingServerAreaEN;
const avgTime = detail.pingResult.rttAvgTime;
const loss = detail.pingResult.lossPacket;
console.log(`${location}: ${avgTime}ms (丢包率: ${loss}%)`);
}
});
})
.catch(error => {
console.error('错误:', error.message);
});
import requests
import os
import json
def ping_test(host, lang='zh', ip_version='ipv4', areas=['all'], count=4):
"""从多个全球位置执行 ping 测试"""
# 从环境变量获取 API 密钥
api_key = os.getenv("IPCONFIG_API_KEY")
if not api_key:
raise ValueError("请设置 IPCONFIG_API_KEY 环境变量")
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"host": host,
"lang": lang,
"ipVersion": ip_version,
"areas": areas,
"count": count
}
try:
response = requests.post(
"https://ipconfig.com/api/ping",
headers=headers,
json=payload,
timeout=30 # Ping 测试可能需要更长时间
)
response.raise_for_status()
data = response.json()
if data.get("success"):
return data["data"]
else:
raise Exception(f"API 错误: {data.get('error', '未知错误')}")
except requests.exceptions.RequestException as e:
raise Exception(f"请求失败: {e}")
def analyze_ping_results(result):
"""分析并显示 ping 测试结果"""
print(f"{result['pingHost']} 的 Ping 测试结果:")
print(f"IP 版本: {result['IPversion']}")
print(f"成功率: {result['successNodes']}/{result['totalNodes']}")
print(f"失败节点: {result['failedNodes']}")
print("\n详细结果:")
print("-" * 80)
successful_results = []
for detail in result['pingResultDetail']:
location = detail.get('pingServerArea', detail.get('pingServerAreaEN', '未知'))
continent = detail.get('continent', '未知')
if detail['result'] and detail.get('pingResult'):
ping_result = detail['pingResult']
avg_time = ping_result['rttAvgTime']
min_time = ping_result['rttMinTime']
max_time = ping_result['rttMaxTime']
loss = ping_result['lossPacket']
ip = ping_result['pingIP']
successful_results.append({
'location': location,
'continent': continent,
'avg_time': avg_time,
'ip': ip
})
print(f"{location:15} ({continent:12}): {avg_time:6.2f}ms "
f"(最小: {min_time:5.2f}ms, 最大: {max_time:5.2f}ms, 丢包: {loss:4.1f}%) "
f"- IP: {ip}")
else:
print(f"{location:15} ({continent:12}): 失败 - {detail.get('message', '未知错误')}")
# 显示最快的位置
if successful_results:
successful_results.sort(key=lambda x: x['avg_time'])
print(f"\n最快的位置:")
for i, result in enumerate(successful_results[:3], 1):
print(f"{i}. {result['location']} ({result['continent']}): {result['avg_time']:.2f}ms")
# 使用示例
if __name__ == "__main__":
try:
# 测试特定位置
result = ping_test(
host="google.com",
areas=["beijing", "tokyo", "california", "london"],
count=4
)
analyze_ping_results(result)
except Exception as e:
print(f"错误: {e}")
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"sort"
"strings"
"time"
)
type PingRequest struct {
Host string `json:"host"`
Lang string `json:"lang"`
IPVersion string `json:"ipVersion"`
Areas []string `json:"areas"`
Count int `json:"count"`
}
type APIResponse struct {
Success bool `json:"success"`
Data *PingData `json:"data,omitempty"`
Error string `json:"error,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
type Meta struct {
IsLoggedIn bool `json:"isLoggedIn"`
IsApiRequest bool `json:"isApiRequest"`
CurrentCredits int `json:"currentCredits"`
}
type PingData struct {
Result bool `json:"result"`
Code string `json:"code"`
Message string `json:"message"`
PingHost string `json:"pingHost"`
IPVersion string `json:"IPversion"`
TotalNodes int `json:"totalNodes"`
SuccessNodes int `json:"successNodes"`
FailedNodes int `json:"failedNodes"`
PingResultDetail []PingResultDetail `json:"pingResultDetail"`
}
type PingResultDetail struct {
Result bool `json:"result"`
Code string `json:"code"`
Message string `json:"message"`
Continent string `json:"continent,omitempty"`
PingServerArea string `json:"pingServerArea"`
PingServerAreaEN string `json:"pingServerAreaEN,omitempty"`
PingResult *PingResult `json:"pingResult,omitempty"`
PingIPLocation *PingIPLocation `json:"pingIPLocation,omitempty"`
}
type PingResult struct {
LossPacket float64 `json:"lossPacket"`
PingHost string `json:"pingHost"`
PingIP string `json:"pingIP"`
PingStatisticsDetail string `json:"pingStatisticsDetail"`
ReceivedPackets int `json:"receivedPackets"`
RttAvgTime float64 `json:"rttAvgTime"`
RttMaxTime float64 `json:"rttMaxTime"`
RttMdevTime float64 `json:"rttMdevTime"`
RttMinTime float64 `json:"rttMinTime"`
SendPackets int `json:"sendPackets"`
TotalElapsedTime int `json:"totalElapsedTime"`
}
type PingIPLocation struct {
Address string `json:"Address"`
ISP string `json:"ISP"`
ASN string `json:"asn"`
}
type LocationResult struct {
Location string
Continent string
AvgTime float64
IP string
}
func pingTest(host, lang, ipVersion string, areas []string, count int) (*PingData, error) {
// 从环境变量获取 API 密钥
apiKey := os.Getenv("IPCONFIG_API_KEY")
if apiKey == "" {
return nil, fmt.Errorf("未设置 IPCONFIG_API_KEY 环境变量")
}
// 准备请求载荷
payload := PingRequest{
Host: host,
Lang: lang,
IPVersion: ipVersion,
Areas: areas,
Count: count,
}
jsonData, err := json.Marshal(payload)
if err != nil {
return nil, fmt.Errorf("JSON 序列化失败: %v", err)
}
// 创建请求
req, err := http.NewRequest("POST", "https://ipconfig.com/api/ping", bytes.NewBuffer(jsonData))
if err != nil {
return nil, fmt.Errorf("创建请求失败: %v", err)
}
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("Content-Type", "application/json")
// 发送请求,ping 测试需要更长的超时时间
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("请求失败: %v", err)
}
defer resp.Body.Close()
// 解析响应
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("读取响应失败: %v", err)
}
var apiResp APIResponse
if err := json.Unmarshal(body, &apiResp); err != nil {
return nil, fmt.Errorf("JSON 解析失败: %v", err)
}
if !apiResp.Success {
return nil, fmt.Errorf("API 错误: %s", apiResp.Error)
}
return apiResp.Data, nil
}
func analyzePingResults(result *PingData) {
fmt.Printf("%s 的 Ping 测试结果:\n", result.PingHost)
fmt.Printf("IP 版本: %s\n", result.IPVersion)
fmt.Printf("成功率: %d/%d\n", result.SuccessNodes, result.TotalNodes)
fmt.Printf("失败节点: %d\n", result.FailedNodes)
fmt.Println("\n详细结果:")
fmt.Println(strings.Repeat("-", 80))
var successfulResults []LocationResult
for _, detail := range result.PingResultDetail {
location := detail.PingServerArea
if location == "" {
location = detail.PingServerAreaEN
}
continent := detail.Continent
if continent == "" {
continent = "未知"
}
if detail.Result && detail.PingResult != nil {
pingResult := detail.PingResult
successfulResults = append(successfulResults, LocationResult{
Location: location,
Continent: continent,
AvgTime: pingResult.RttAvgTime,
IP: pingResult.PingIP,
})
fmt.Printf("%-15s (%-12s): %6.2fms (最小: %5.2fms, 最大: %5.2fms, 丢包: %4.1f%%) - IP: %s\n",
location, continent,
pingResult.RttAvgTime,
pingResult.RttMinTime,
pingResult.RttMaxTime,
pingResult.LossPacket,
pingResult.PingIP)
} else {
fmt.Printf("%-15s (%-12s): 失败 - %s\n", location, continent, detail.Message)
}
}
// 显示最快的位置
if len(successfulResults) > 0 {
sort.Slice(successfulResults, func(i, j int) bool {
return successfulResults[i].AvgTime < successfulResults[j].AvgTime
})
fmt.Println("\n最快的位置:")
for i, result := range successfulResults {
if i >= 3 {
break
}
fmt.Printf("%d. %s (%s): %.2fms\n", i+1, result.Location, result.Continent, result.AvgTime)
}
}
}
func main() {
result, err := pingTest(
"google.com",
"zh",
"ipv4",
[]string{"beijing", "tokyo", "california", "london"},
4,
)
if err != nil {
fmt.Printf("Ping 测试失败: %v\n", err)
return
}
analyzePingResults(result)
}
<?php
function pingTest($host, $options = []) {
// 从环境变量获取 API 密钥
$apiKey = getenv('IPCONFIG_API_KEY');
if (!$apiKey) {
throw new Exception('未设置 IPCONFIG_API_KEY 环境变量');
}
$defaults = [
'lang' => 'zh',
'ipVersion' => 'ipv4',
'areas' => ['all'],
'count' => 4
];
$options = array_merge($defaults, $options);
$payload = json_encode([
'host' => $host,
'lang' => $options['lang'],
'ipVersion' => $options['ipVersion'],
'areas' => $options['areas'],
'count' => $options['count']
]);
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => [
'Content-Type: application/json',
'Authorization: Bearer ' . $apiKey
],
'content' => $payload,
'timeout' => 30 // Ping 测试可能需要更长时间
]
]);
$response = file_get_contents('https://ipconfig.com/api/ping', false, $context);
if ($response === false) {
throw new Exception('请求失败');
}
$data = json_decode($response, true);
if (!$data['success']) {
throw new Exception('API 错误: ' . ($data['error'] ?? '未知错误'));
}
return $data['data'];
}
function analyzePingResults($result) {
echo "{$result['pingHost']} 的 Ping 测试结果:\n";
echo "IP 版本: {$result['IPversion']}\n";
echo "成功率: {$result['successNodes']}/{$result['totalNodes']}\n";
echo "失败节点: {$result['failedNodes']}\n";
echo "\n详细结果:\n";
echo str_repeat("-", 80) . "\n";
$successfulResults = [];
foreach ($result['pingResultDetail'] as $detail) {
$location = $detail['pingServerArea'] ?? $detail['pingServerAreaEN'] ?? '未知';
$continent = $detail['continent'] ?? '未知';
if ($detail['result'] && isset($detail['pingResult'])) {
$pingResult = $detail['pingResult'];
$successfulResults[] = [
'location' => $location,
'continent' => $continent,
'avgTime' => $pingResult['rttAvgTime'],
'ip' => $pingResult['pingIP']
];
printf("%-15s (%-12s): %6.2fms (最小: %5.2fms, 最大: %5.2fms, 丢包: %4.1f%%) - IP: %s\n",
$location, $continent,
$pingResult['rttAvgTime'],
$pingResult['rttMinTime'],
$pingResult['rttMaxTime'],
$pingResult['lossPacket'],
$pingResult['pingIP']
);
} else {
printf("%-15s (%-12s): 失败 - %s\n", $location, $continent, $detail['message'] ?? '未知错误');
}
}
// 显示最快的位置
if (!empty($successfulResults)) {
usort($successfulResults, function($a, $b) {
return $a['avgTime'] <=> $b['avgTime'];
});
echo "\n最快的位置:\n";
for ($i = 0; $i < min(3, count($successfulResults)); $i++) {
$result = $successfulResults[$i];
printf("%d. %s (%s): %.2fms\n", $i + 1, $result['location'], $result['continent'], $result['avgTime']);
}
}
}
// 使用示例
try {
$result = pingTest('google.com', [
'areas' => ['beijing', 'tokyo', 'california', 'london'],
'count' => 4
]);
analyzePingResults($result);
} catch (Exception $e) {
echo "错误: " . $e->getMessage() . "\n";
}
?>
响应格式
成功响应
{
"success": true,
"data": {
"result": true,
"code": "PingSuccess",
"message": "Ping 成功",
"pingHost": "google.com",
"IPversion": "ipv4",
"totalNodes": 4,
"successNodes": 4,
"failedNodes": 0,
"pingResultDetail": [
{
"result": true,
"code": "PingSuccess",
"message": "Ping 成功",
"continent": "亚洲",
"pingServerArea": "北京",
"pingServerAreaEN": "Beijing",
"pingResult": {
"lossPacket": 0,
"pingHost": "google.com",
"pingIP": "142.250.196.14",
"pingStatisticsDetail": "PING google.com (142.250.196.14) 56(84) bytes of data...",
"receivedPackets": 4,
"rttAvgTime": 45.234,
"rttMaxTime": 48.123,
"rttMdevTime": 1.234,
"rttMinTime": 42.567,
"sendPackets": 4,
"totalElapsedTime": 3045
},
"pingIPLocation": {
"Address": "美国,加利福尼亚州,山景城",
"ISP": "Google LLC",
"asn": "AS15169"
}
}
]
},
"meta": {
"isLoggedIn": true,
"isApiRequest": true,
"currentCredits": 1234
}
}
错误响应
{
"success": false,
"error": "主机名或 IP 地址无效",
"meta": {
"isLoggedIn": true,
"isApiRequest": true,
"currentCredits": 1234
}
}
响应字段
主要响应
字段 | 类型 | 描述 |
---|---|---|
result | boolean | 整体 ping 测试成功状态 |
code | string | 结果代码 |
message | string | 结果消息 |
pingHost | string | 目标主机名/IP |
IPversion | string | 使用的 IP 版本 |
totalNodes | number | 总测试位置数 |
successNodes | number | 成功的测试位置数 |
failedNodes | number | 失败的测试位置数 |
pingResultDetail | array | 每个位置的详细结果 |
Ping 结果详情
字段 | 类型 | 描述 |
---|---|---|
result | boolean | 此位置的成功状态 |
continent | string | 大洲名称 |
pingServerArea | string | 位置名称(本地语言) |
pingServerAreaEN | string | 位置名称(英语) |
pingResult | object | 详细 ping 统计信息 |
pingIPLocation | object | 目标 IP 位置信息 |
Ping 统计信息
字段 | 类型 | 描述 |
---|---|---|
lossPacket | number | 丢包百分比 |
pingIP | string | 解析的 IP 地址 |
receivedPackets | number | 接收的数据包数 |
sendPackets | number | 发送的数据包数 |
rttAvgTime | number | 平均响应时间(毫秒) |
rttMinTime | number | 最小响应时间(毫秒) |
rttMaxTime | number | 最大响应时间(毫秒) |
rttMdevTime | number | 标准偏差(毫秒) |
totalElapsedTime | number | 总测试时间(毫秒) |
错误代码
代码 | 描述 |
---|---|
InvalidHost | 主机名或 IP 地址无效 |
HostNotFound | 无法解析主机名 |
TimeoutError | Ping 测试超时 |
NetworkError | 网络连接问题 |
RateLimitExceeded | API 速率限制超出 |
InsufficientCredits | API 积分不足 |
InvalidAPIKey | API 密钥无效或缺失 |
速率限制和定价
- 免费版:每月 100 次 ping 测试
- 专业版:每月 1,000 次 ping 测试
- 企业版:可定制限制
每次 ping 测试按测试位置消耗积分。测试"所有"位置将使用所有可用位置的积分。
最佳实践
- 选择相关位置:选择与您的用户相关的测试位置
- 合理的包数量:使用 2-4 个包在准确性和速度之间取得平衡
- 处理超时:Ping 测试可能需要 10-30 秒完成
- 缓存结果:网络条件变化不快,可缓存 5-15 分钟
- 监控积分:Ping 测试比其他 API 消耗更多积分
使用场景
- CDN 性能:测试内容分发网络性能
- 服务器监控:监控服务器从不同地区的可访问性
- 网络诊断:排查连接问题
- 性能优化:识别最佳服务器位置
- SLA 监控:跟踪服务级别协议合规性
- 负载均衡器测试:验证全球负载均衡器性能
限制
- IPv6 支持:可用的 IPv6 测试位置有限
- 私有 IP:无法 ping 私有/内网 IP 地址
- 防火墙限制:某些主机可能阻止 ICMP ping 包
- 测试持续时间:测试可能需要 10-30 秒,取决于位置和包数量
相关 API
- 获取我的 IP API - 获取您当前的公网 IP 地址
- IP 归属地查询 API - 获取任何 IP 的详细位置信息