LogoIPCONFIG Docs

Ping Test API

Test network connectivity and latency to global locations

Overview

The Ping Test API allows you to test network connectivity and measure latency from multiple global locations to any hostname or IP address. Get detailed ping statistics including packet loss, response times, and network path information.

Endpoint

POST https://ipconfig.com/api/ping

Authentication

This API requires authentication using an API key. Include your API key in the request headers:

Authorization: Bearer YOUR_API_KEY

Get your API key →

Request Format

Headers

Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

Body Parameters

ParameterTypeRequiredDescription
hoststringYesTarget hostname or IP address to ping
langstringNoResponse language (en or zh). Default: en
ipVersionstringNoIP version (ipv4 or ipv6). Default: ipv4
areasarrayNoTest locations. Use ["all"] for all locations or specify individual areas
countnumberNoNumber of ping packets to send (1-10). Default: 4

Example Request

{
  "host": "google.com",
  "lang": "en",
  "ipVersion": "ipv4",
  "areas": ["beijing", "tokyo", "california", "london"],
  "count": 4
}

Available Test Locations

Asia Pacific

  • beijing - Beijing, China
  • nanjing - Nanjing, China
  • chengdu - Chengdu, China
  • guangzhou - Guangzhou, China
  • hongkong - Hong Kong
  • taiwan - Taiwan
  • singapore - Singapore
  • tokyo - Tokyo, Japan
  • seoul - Seoul, South Korea
  • mumbai - Mumbai, India
  • sydney - Sydney, Australia

Europe & Middle East

  • doha - Doha, Qatar
  • frankfurt - Frankfurt, Germany
  • london - London, UK
  • moscow - Moscow, Russia
  • johannesburg - Johannesburg, South Africa

Americas

  • california - California, USA
  • virginia - Virginia, USA
  • dallas - Dallas, USA
  • chicago - Chicago, USA
  • seattle - Seattle, USA
  • miami - Miami, USA
  • newark - Newark, USA
  • saopaulo - São Paulo, Brazil

Usage Examples

# Set your API key
export IPCONFIG_API_KEY='your-api-key-here'

# Test specific locations
curl -H "Content-Type: application/json" \
  -H "Authorization: Bearer $IPCONFIG_API_KEY" \
  "https://ipconfig.com/api/ping" \
  -d '{
    "host": "google.com",
    "lang": "en",
    "ipVersion": "ipv4",
    "areas": ["beijing", "tokyo", "california"],
    "count": 4
  }'

# Test all locations
curl -H "Content-Type: application/json" \
  -H "Authorization: Bearer $IPCONFIG_API_KEY" \
  "https://ipconfig.com/api/ping" \
  -d '{
    "host": "example.com",
    "lang": "en",
    "ipVersion": "ipv4",
    "areas": ["all"],
    "count": 2
  }'
async function pingTest(host, options = {}) {
  const apiKey = process.env.IPCONFIG_API_KEY;

  if (!apiKey) {
    throw new Error('API key not configured');
  }

  const {
    lang = 'en',
    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 error! status: ${response.status}`);
    }

    const data = await response.json();

    if (data.success) {
      return data.data;
    } else {
      throw new Error(data.error || 'Unknown API error');
    }
  } catch (error) {
    console.error('Ping test failed:', error);
    throw error;
  }
}

// Usage example
pingTest('google.com', {
  areas: ['beijing', 'tokyo', 'california'],
  count: 4
})
.then(result => {
  console.log(`Ping test for ${result.pingHost}:`);
  console.log(`Success rate: ${result.successNodes}/${result.totalNodes}`);

  result.pingResultDetail.forEach(detail => {
    if (detail.result && detail.pingResult) {
      const location = detail.pingServerAreaEN || detail.pingServerArea;
      const avgTime = detail.pingResult.rttAvgTime;
      const loss = detail.pingResult.lossPacket;
      console.log(`${location}: ${avgTime}ms (${loss}% loss)`);
    }
  });
})
.catch(error => {
  console.error('Error:', error.message);
});
import requests
import os
import json

def ping_test(host, lang='en', ip_version='ipv4', areas=['all'], count=4):
    """Perform ping test from multiple global locations"""

    # Get API key from environment variable
    api_key = os.getenv("IPCONFIG_API_KEY")
    if not api_key:
        raise ValueError("Please set IPCONFIG_API_KEY environment variable")

    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 tests can take longer
        )
        response.raise_for_status()

        data = response.json()

        if data.get("success"):
            return data["data"]
        else:
            raise Exception(f"API Error: {data.get('error', 'Unknown error')}")

    except requests.exceptions.RequestException as e:
        raise Exception(f"Request failed: {e}")

def analyze_ping_results(result):
    """Analyze and display ping test results"""
    print(f"Ping test results for {result['pingHost']}:")
    print(f"IP Version: {result['IPversion']}")
    print(f"Success Rate: {result['successNodes']}/{result['totalNodes']}")
    print(f"Failed Nodes: {result['failedNodes']}")
    print("\nDetailed Results:")
    print("-" * 80)

    successful_results = []

    for detail in result['pingResultDetail']:
        location = detail.get('pingServerAreaEN', detail['pingServerArea'])
        continent = detail.get('continent', 'Unknown')

        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: {min_time:5.2f}ms, max: {max_time:5.2f}ms, loss: {loss:4.1f}%) "
                  f"- IP: {ip}")
        else:
            print(f"{location:15} ({continent:12}): FAILED - {detail.get('message', 'Unknown error')}")

    # Show fastest locations
    if successful_results:
        successful_results.sort(key=lambda x: x['avg_time'])
        print(f"\nFastest locations:")
        for i, result in enumerate(successful_results[:3], 1):
            print(f"{i}. {result['location']} ({result['continent']}): {result['avg_time']:.2f}ms")

# Usage example
if __name__ == "__main__":
    try:
        # Test specific locations
        result = ping_test(
            host="google.com",
            areas=["beijing", "tokyo", "california", "london"],
            count=4
        )

        analyze_ping_results(result)

    except Exception as e:
        print(f"Error: {e}")
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "sort"
    "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) {
    // Get API key from environment variable
    apiKey := os.Getenv("IPCONFIG_API_KEY")
    if apiKey == "" {
        return nil, fmt.Errorf("IPCONFIG_API_KEY environment variable not set")
    }

    // Prepare request payload
    payload := PingRequest{
        Host:      host,
        Lang:      lang,
        IPVersion: ipVersion,
        Areas:     areas,
        Count:     count,
    }

    jsonData, err := json.Marshal(payload)
    if err != nil {
        return nil, fmt.Errorf("failed to marshal JSON: %v", err)
    }

    // Create request
    req, err := http.NewRequest("POST", "https://ipconfig.com/api/ping", bytes.NewBuffer(jsonData))
    if err != nil {
        return nil, fmt.Errorf("failed to create request: %v", err)
    }

    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    // Send request with longer timeout for ping tests
    client := &http.Client{Timeout: 30 * time.Second}
    resp, err := client.Do(req)
    if err != nil {
        return nil, fmt.Errorf("request failed: %v", err)
    }
    defer resp.Body.Close()

    // Parse response
    body, err := io.ReadAll(resp.Body)
    if err != nil {
        return nil, fmt.Errorf("failed to read response: %v", err)
    }

    var apiResp APIResponse
    if err := json.Unmarshal(body, &apiResp); err != nil {
        return nil, fmt.Errorf("failed to parse JSON: %v", err)
    }

    if !apiResp.Success {
        return nil, fmt.Errorf("API error: %s", apiResp.Error)
    }

    return apiResp.Data, nil
}

func analyzePingResults(result *PingData) {
    fmt.Printf("Ping test results for %s:\n", result.PingHost)
    fmt.Printf("IP Version: %s\n", result.IPVersion)
    fmt.Printf("Success Rate: %d/%d\n", result.SuccessNodes, result.TotalNodes)
    fmt.Printf("Failed Nodes: %d\n", result.FailedNodes)
    fmt.Println("\nDetailed Results:")
    fmt.Println(strings.Repeat("-", 80))

    var successfulResults []LocationResult

    for _, detail := range result.PingResultDetail {
        location := detail.PingServerAreaEN
        if location == "" {
            location = detail.PingServerArea
        }
        continent := detail.Continent
        if continent == "" {
            continent = "Unknown"
        }

        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 (min: %5.2fms, max: %5.2fms, loss: %4.1f%%) - IP: %s\n",
                location, continent,
                pingResult.RttAvgTime,
                pingResult.RttMinTime,
                pingResult.RttMaxTime,
                pingResult.LossPacket,
                pingResult.PingIP)
        } else {
            fmt.Printf("%-15s (%-12s): FAILED - %s\n", location, continent, detail.Message)
        }
    }

    // Show fastest locations
    if len(successfulResults) > 0 {
        sort.Slice(successfulResults, func(i, j int) bool {
            return successfulResults[i].AvgTime < successfulResults[j].AvgTime
        })

        fmt.Println("\nFastest locations:")
        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",
        "en",
        "ipv4",
        []string{"beijing", "tokyo", "california", "london"},
        4,
    )
    if err != nil {
        fmt.Printf("Ping test failed: %v\n", err)
        return
    }

    analyzePingResults(result)
}
<?php

function pingTest($host, $options = []) {
    // Get API key from environment variable
    $apiKey = getenv('IPCONFIG_API_KEY');
    if (!$apiKey) {
        throw new Exception('IPCONFIG_API_KEY environment variable not set');
    }

    $defaults = [
        'lang' => 'en',
        '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 tests can take longer
        ]
    ]);

    $response = file_get_contents('https://ipconfig.com/api/ping', false, $context);

    if ($response === false) {
        throw new Exception('Request failed');
    }

    $data = json_decode($response, true);

    if (!$data['success']) {
        throw new Exception('API Error: ' . ($data['error'] ?? 'Unknown error'));
    }

    return $data['data'];
}

function analyzePingResults($result) {
    echo "Ping test results for {$result['pingHost']}:\n";
    echo "IP Version: {$result['IPversion']}\n";
    echo "Success Rate: {$result['successNodes']}/{$result['totalNodes']}\n";
    echo "Failed Nodes: {$result['failedNodes']}\n";
    echo "\nDetailed Results:\n";
    echo str_repeat("-", 80) . "\n";

    $successfulResults = [];

    foreach ($result['pingResultDetail'] as $detail) {
        $location = $detail['pingServerAreaEN'] ?? $detail['pingServerArea'];
        $continent = $detail['continent'] ?? 'Unknown';

        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 (min: %5.2fms, max: %5.2fms, loss: %4.1f%%) - IP: %s\n",
                $location, $continent,
                $pingResult['rttAvgTime'],
                $pingResult['rttMinTime'],
                $pingResult['rttMaxTime'],
                $pingResult['lossPacket'],
                $pingResult['pingIP']
            );
        } else {
            printf("%-15s (%-12s): FAILED - %s\n", $location, $continent, $detail['message'] ?? 'Unknown error');
        }
    }

    // Show fastest locations
    if (!empty($successfulResults)) {
        usort($successfulResults, function($a, $b) {
            return $a['avgTime'] <=> $b['avgTime'];
        });

        echo "\nFastest locations:\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']);
        }
    }
}

// Usage example
try {
    $result = pingTest('google.com', [
        'areas' => ['beijing', 'tokyo', 'california', 'london'],
        'count' => 4
    ]);

    analyzePingResults($result);

} catch (Exception $e) {
    echo "Error: " . $e->getMessage() . "\n";
}

?>

Response Format

Success Response

{
  "success": true,
  "data": {
    "result": true,
    "code": "PingSuccess",
    "message": "Ping Success",
    "pingHost": "google.com",
    "IPversion": "ipv4",
    "totalNodes": 4,
    "successNodes": 4,
    "failedNodes": 0,
    "pingResultDetail": [
      {
        "result": true,
        "code": "PingSuccess",
        "message": "Ping Success",
        "continent": "Asia",
        "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": "United States,California,Mountain View",
          "ISP": "Google LLC",
          "asn": "AS15169"
        }
      }
    ]
  },
  "meta": {
    "isLoggedIn": true,
    "isApiRequest": true,
    "currentCredits": 1234
  }
}

Error Response

{
  "success": false,
  "error": "Invalid hostname or IP address",
  "meta": {
    "isLoggedIn": true,
    "isApiRequest": true,
    "currentCredits": 1234
  }
}

Response Fields

Main Response

FieldTypeDescription
resultbooleanOverall ping test success
codestringResult code
messagestringResult message
pingHoststringTarget hostname/IP
IPversionstringIP version used
totalNodesnumberTotal test locations
successNodesnumberSuccessful test locations
failedNodesnumberFailed test locations
pingResultDetailarrayDetailed results per location

Ping Result Detail

FieldTypeDescription
resultbooleanSuccess status for this location
continentstringContinent name
pingServerAreastringLocation name (local language)
pingServerAreaENstringLocation name (English)
pingResultobjectDetailed ping statistics
pingIPLocationobjectTarget IP location info

Ping Statistics

FieldTypeDescription
lossPacketnumberPacket loss percentage
pingIPstringResolved IP address
receivedPacketsnumberPackets received
sendPacketsnumberPackets sent
rttAvgTimenumberAverage response time (ms)
rttMinTimenumberMinimum response time (ms)
rttMaxTimenumberMaximum response time (ms)
rttMdevTimenumberStandard deviation (ms)
totalElapsedTimenumberTotal test time (ms)

Error Codes

CodeDescription
InvalidHostInvalid hostname or IP address
HostNotFoundHostname could not be resolved
TimeoutErrorPing test timed out
NetworkErrorNetwork connectivity issue
RateLimitExceededAPI rate limit exceeded
InsufficientCreditsNot enough API credits
InvalidAPIKeyInvalid or missing API key

Rate Limits & Pricing

  • Free Tier: 100 ping tests per month
  • Pro Tier: 1,000 ping tests per month
  • Enterprise: Custom limits available

Each ping test consumes 1 credit per test location. Testing "all" locations uses credits for all available locations.

Best Practices

  1. Choose Relevant Locations: Select test locations relevant to your users
  2. Reasonable Packet Count: Use 2-4 packets for balance between accuracy and speed
  3. Handle Timeouts: Ping tests can take 10-30 seconds to complete
  4. Cache Results: Network conditions don't change rapidly, cache for 5-15 minutes
  5. Monitor Credits: Ping tests consume more credits than other APIs

Use Cases

  • CDN Performance: Test content delivery network performance
  • Server Monitoring: Monitor server accessibility from different regions
  • Network Diagnostics: Troubleshoot connectivity issues
  • Performance Optimization: Identify optimal server locations
  • SLA Monitoring: Track service level agreement compliance
  • Load Balancer Testing: Verify global load balancer performance

Limitations

  • IPv6 Support: Limited IPv6 test locations available
  • Private IPs: Cannot ping private/internal IP addresses
  • Firewall Restrictions: Some hosts may block ICMP ping packets
  • Test Duration: Tests may take 10-30 seconds depending on locations and packet count