LogoIPCONFIG 文档

IP 归属地查询 API

获取任何 IP 地址的详细位置信息

概述

IP 归属地查询 API 为任何 IPv4 或 IPv6 地址提供全面的地理位置信息。获取详细的位置数据,包括国家、地区、城市、ISP、时区和坐标。

接口地址

POST https://ipconfig.com/api/ip-query

身份验证

此 API 需要使用 API 密钥进行身份验证。在请求头中包含您的 API 密钥:

Authorization: Bearer YOUR_API_KEY

获取您的 API 密钥 →

请求格式

请求头

Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

请求参数

参数类型必需描述
ipstring要查询的 IP 地址(IPv4 或 IPv6)
langstring响应语言(enzh)。默认:en

请求示例

{
  "ip": "8.8.8.8",
  "lang": "zh"
}

使用示例

# 设置您的 API 密钥
export IPCONFIG_API_KEY='your-api-key-here'

# 基础 IP 查询
curl -H "Content-Type: application/json" \
  -H "Authorization: Bearer $IPCONFIG_API_KEY" \
  -X POST "https://ipconfig.com/api/ip-query" \
  -d '{
    "ip": "8.8.8.8",
    "lang": "zh"
  }'

# 查询 IPv6 地址
curl -H "Content-Type: application/json" \
  -H "Authorization: Bearer $IPCONFIG_API_KEY" \
  -X POST "https://ipconfig.com/api/ip-query" \
  -d '{
    "ip": "2001:4860:4860::8888",
    "lang": "zh"
  }'
async function queryIPLocation(ip, lang = 'zh') {
  const apiKey = process.env.IPCONFIG_API_KEY;

  if (!apiKey) {
    throw new Error('API 密钥未配置');
  }

  try {
    const response = await fetch('https://ipconfig.com/api/ip-query', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ ip, lang })
    });

    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('IP 查询失败:', error);
    throw error;
  }
}

// 使用示例
queryIPLocation('8.8.8.8', 'zh')
  .then(result => {
    console.log('IP 位置信息:', result);
    console.log(`位置: ${result.city}, ${result.country}`);
    console.log(`ISP: ${result.isp}`);
    console.log(`坐标: ${result.latitude}, ${result.longitude}`);
  })
  .catch(error => {
    console.error('错误:', error.message);
  });
import requests
import os
import json

def query_ip_location(ip_address, lang='zh'):
    """查询 IP 位置信息"""

    # 从环境变量获取 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 = {
        "ip": ip_address,
        "lang": lang
    }

    try:
        response = requests.post(
            "https://ipconfig.com/api/ip-query",
            headers=headers,
            json=payload,
            timeout=10
        )
        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}")

# 使用示例
if __name__ == "__main__":
    try:
        # 查询 Google DNS
        result = query_ip_location("8.8.8.8", "zh")

        print(f"IP: {result['ip']}")
        print(f"国家: {result.get('country', '未知')}")
        print(f"省份: {result.get('province', '未知')}")
        print(f"城市: {result.get('city', '未知')}")
        print(f"ISP: {result.get('isp', '未知')}")
        print(f"ASN: {result.get('asn', '未知')}")
        print(f"位置: {result.get('latitude', 0)}, {result.get('longitude', 0)}")
        print(f"时区: {result.get('time_zone', '未知')}")

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

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
    "os"
    "time"
)

type IPQueryRequest struct {
    IP   string `json:"ip"`
    Lang string `json:"lang"`
}

type APIResponse struct {
    Success bool      `json:"success"`
    Data    *IPResult `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 IPResult struct {
    IP        string  `json:"ip"`
    Continent string  `json:"continent,omitempty"`
    Country   string  `json:"country,omitempty"`
    Province  string  `json:"province,omitempty"`
    City      string  `json:"city,omitempty"`
    District  string  `json:"district,omitempty"`
    ISP       string  `json:"isp,omitempty"`
    ASN       string  `json:"asn,omitempty"`
    Latitude  float64 `json:"latitude,omitempty"`
    Longitude float64 `json:"longitude,omitempty"`
    TimeZone  string  `json:"time_zone,omitempty"`
    Currency  string  `json:"currency,omitempty"`
    ZipCode   string  `json:"zip_code,omitempty"`
    AreaCode  string  `json:"area_code,omitempty"`
}

func queryIPLocation(ipAddress, lang string) (*IPResult, error) {
    // 从环境变量获取 API 密钥
    apiKey := os.Getenv("IPCONFIG_API_KEY")
    if apiKey == "" {
        return nil, fmt.Errorf("未设置 IPCONFIG_API_KEY 环境变量")
    }

    // 准备请求载荷
    payload := IPQueryRequest{
        IP:   ipAddress,
        Lang: lang,
    }

    jsonData, err := json.Marshal(payload)
    if err != nil {
        return nil, fmt.Errorf("JSON 序列化失败: %v", err)
    }

    // 创建请求
    req, err := http.NewRequest("POST", "https://ipconfig.com/api/ip-query", 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")

    // 发送请求
    client := &http.Client{Timeout: 10 * 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 main() {
    result, err := queryIPLocation("8.8.8.8", "zh")
    if err != nil {
        fmt.Printf("查询失败: %v\n", err)
        return
    }

    fmt.Printf("IP: %s\n", result.IP)
    fmt.Printf("国家: %s\n", result.Country)
    fmt.Printf("省份: %s\n", result.Province)
    fmt.Printf("城市: %s\n", result.City)
    fmt.Printf("ISP: %s\n", result.ISP)
    fmt.Printf("ASN: %s\n", result.ASN)
    fmt.Printf("位置: %.6f, %.6f\n", result.Latitude, result.Longitude)
    fmt.Printf("时区: %s\n", result.TimeZone)
}
<?php

function queryIPLocation($ip, $lang = 'zh') {
    // 从环境变量获取 API 密钥
    $apiKey = getenv('IPCONFIG_API_KEY');
    if (!$apiKey) {
        throw new Exception('未设置 IPCONFIG_API_KEY 环境变量');
    }

    $payload = json_encode([
        'ip' => $ip,
        'lang' => $lang
    ]);

    $context = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => [
                'Content-Type: application/json',
                'Authorization: Bearer ' . $apiKey
            ],
            'content' => $payload,
            'timeout' => 10
        ]
    ]);

    $response = file_get_contents('https://ipconfig.com/api/ip-query', 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'];
}

// 使用示例
try {
    $result = queryIPLocation('8.8.8.8', 'zh');

    echo "IP: " . $result['ip'] . "\n";
    echo "国家: " . ($result['country'] ?? '未知') . "\n";
    echo "省份: " . ($result['province'] ?? '未知') . "\n";
    echo "城市: " . ($result['city'] ?? '未知') . "\n";
    echo "ISP: " . ($result['isp'] ?? '未知') . "\n";
    echo "ASN: " . ($result['asn'] ?? '未知') . "\n";
    echo "位置: " . ($result['latitude'] ?? 0) . ", " . ($result['longitude'] ?? 0) . "\n";
    echo "时区: " . ($result['time_zone'] ?? '未知') . "\n";

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

?>

响应格式

成功响应

{
  "success": true,
  "data": {
    "ip": "8.8.8.8",
    "continent": "北美洲",
    "country": "美国",
    "province": "加利福尼亚州",
    "city": "山景城",
    "district": "",
    "isp": "Google LLC",
    "asn": "AS15169",
    "latitude": 37.4056,
    "longitude": -122.0775,
    "time_zone": "America/Los_Angeles",
    "currency": "USD",
    "zip_code": "94043",
    "area_code": "650"
  },
  "meta": {
    "isLoggedIn": true,
    "isApiRequest": true,
    "currentCredits": 1247
  }
}

错误响应

{
  "success": false,
  "error": "IP 地址格式无效",
  "meta": {
    "isLoggedIn": true,
    "isApiRequest": true,
    "currentCredits": 1247
  }
}

响应字段

字段类型描述
ipstring查询的 IP 地址
continentstring大洲名称
countrystring国家名称
provincestring省份/州名称
citystring城市名称
districtstring区/县名称
ispstring互联网服务提供商
asnstring自治系统号
latitudenumber纬度坐标
longitudenumber经度坐标
time_zonestring时区标识符
currencystring当地货币代码
zip_codestring邮政编码
area_codestring电话区号

错误代码

代码描述
InvalidIPIP 地址格式无效
PrivateIP不支持私有 IP 地址
RateLimitExceededAPI 速率限制超出
InsufficientCreditsAPI 积分不足
InvalidAPIKeyAPI 密钥无效或缺失

速率限制

  • 免费版:每月 1,000 次请求
  • 专业版:每月 10,000 次请求
  • 企业版:可定制限制

速率限制按 API 密钥执行。超出限制将返回 429 Too Many Requests 状态。

最佳实践

  1. 缓存结果:IP 位置数据变化不频繁,可缓存 24-48 小时
  2. 优雅处理错误:始终实现适当的错误处理
  3. 验证 IP 地址:在发出请求前验证 IP 格式
  4. 使用适当语言:根据用户偏好设置 lang 参数
  5. 监控积分:跟踪您的 API 积分使用情况

使用场景

  • 地理位置服务:显示基于位置的内容
  • 欺诈检测:识别可疑 IP 地址
  • 数据分析:了解用户地理分布
  • 内容个性化:根据位置定制内容
  • 安全防护:基于位置阻止或允许访问
  • 合规要求:实施法律要求的地理限制

支持的 IP 类型

  • IPv4:标准 IPv4 地址(如 192.168.1.1
  • 仅公网 IP:不支持私有/内网 IP 地址

相关 API