使用Golang通过IP2Location.io CLI工具获取IP地理位置信息

使用Golang通过IP2Location.io CLI工具获取IP地理位置信息 GitHub 链接:https://github.com/ip2location/ip2location-io-cli

地理位置命令行界面,旨在帮助 IT 管理员轻松分析数据并生成报告。

IP2Location.io CLI 为您的命令行提供地理位置查询能力,返回用于分析和报告的丰富数据。

从国家、地区、区县、城市等详细的地理信息,到经纬度等精确坐标,我们的工具一应俱全。此外,您还可以探索更多信息,例如邮政编码、时区、ASN、ISP、域名、网络速度、国际长途区号、国内区号、气象站数据、MNC、MCC、移动设备品牌、海拔高度、使用类型、地址类型、广告类别,甚至代理数据。它支持 IPv4 和 IPv6 地址查询。


更多关于使用Golang通过IP2Location.io CLI工具获取IP地理位置信息的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于使用Golang通过IP2Location.io CLI工具获取IP地理位置信息的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"strings"
)

// IP2Location 数据结构
type IP2Location struct {
	IP                 string  `json:"ip"`
	CountryCode        string  `json:"country_code"`
	CountryName        string  `json:"country_name"`
	RegionName         string  `json:"region_name"`
	CityName           string  `json:"city_name"`
	Latitude           float64 `json:"latitude"`
	Longitude          float64 `json:"longitude"`
	ZipCode            string  `json:"zip_code"`
	TimeZone           string  `json:"time_zone"`
	ASN                string  `json:"asn"`
	AS                 string  `json:"as"`
	ISP                string  `json:"isp"`
	Domain             string  `json:"domain"`
	NetSpeed           string  `json:"net_speed"`
	IDDCode            string  `json:"idd_code"`
	AreaCode           string  `json:"area_code"`
	WeatherStationCode string  `json:"weather_station_code"`
	WeatherStationName string  `json:"weather_station_name"`
	MCC                string  `json:"mcc"`
	MNC                string  `json:"mnc"`
	MobileBrand        string  `json:"mobile_brand"`
	Elevation          int     `json:"elevation"`
	UsageType          string  `json:"usage_type"`
	AddressType        string  `json:"address_type"`
	Continent          struct {
		Name        string `json:"name"`
		Code        string `json:"code"`
		Hemisphere  string `json:"hemisphere"`
		Translation struct {
			ZhCN string `json:"zh-cn"`
		} `json:"translation"`
	} `json:"continent"`
	Country struct {
		Name        string `json:"name"`
		Alpha3Code  string `json:"alpha3_code"`
		NumericCode int    `json:"numeric_code"`
		Demonym     string `json:"demonym"`
		Flag        string `json:"flag"`
		Capital     string `json:"capital"`
		TotalArea   int    `json:"total_area"`
		Population  int    `json:"population"`
		Currency    struct {
			Code   string `json:"code"`
			Name   string `json:"name"`
			Symbol string `json:"symbol"`
		} `json:"currency"`
		Language struct {
			Code string `json:"code"`
			Name string `json:"name"`
		} `json:"language"`
		IDDCode string `json:"idd_code"`
		TLD     string `json:"tld"`
		Translation struct {
			ZhCN string `json:"zh-cn"`
		} `json:"translation"`
	} `json:"country"`
	Region struct {
		Name        string `json:"name"`
		Code        string `json:"code"`
		Translation struct {
			ZhCN string `json:"zh-cn"`
		} `json:"translation"`
	} `json:"region"`
	City struct {
		Name        string `json:"name"`
		Translation struct {
			ZhCN string `json:"zh-cn"`
		} `json:"translation"`
	} `json:"city"`
	TimeZoneInfo struct {
		Olson       string `json:"olson"`
		CurrentTime string `json:"current_time"`
		GMTOffset   int    `json:"gmt_offset"`
		IsDST       bool   `json:"is_dst"`
		Sunrise     string `json:"sunrise"`
		Sunset      string `json:"sunset"`
	} `json:"time_zone_info"`
	Geotargeting struct {
		Metro string `json:"metro"`
	} `json:"geotargeting"`
	ADS struct {
		Category string `json:"category"`
	} `json:"ads"`
	Proxy struct {
		LastSeen   int    `json:"last_seen"`
		ProxyType  string `json:"proxy_type"`
		Threat     string `json:"threat"`
		Provider   string `json:"provider"`
		IsVPN      bool   `json:"is_vpn"`
		IsTor      bool   `json:"is_tor"`
		IsDataCenter bool `json:"is_data_center"`
		IsPublicProxy bool `json:"is_public_proxy"`
		IsWebProxy bool   `json:"is_web_proxy"`
		IsWebCrawler bool `json:"is_web_crawler"`
		IsResidentialProxy bool `json:"is_residential_proxy"`
	} `json:"proxy"`
}

// 方法1: 直接调用CLI工具
func GetIPLocationCLI(ip string) (string, error) {
	cmd := exec.Command("ip2locationio", "lookup", ip)
	output, err := cmd.Output()
	if err != nil {
		return "", fmt.Errorf("CLI执行失败: %v", err)
	}
	return string(output), nil
}

// 方法2: 通过API调用(推荐)
func GetIPLocationAPI(ip, apiKey string) (*IP2Location, error) {
	url := fmt.Sprintf("https://api.ip2location.io/?key=%s&ip=%s", apiKey, ip)
	
	resp, err := http.Get(url)
	if err != nil {
		return nil, fmt.Errorf("API请求失败: %v", err)
	}
	defer resp.Body.Close()
	
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取响应失败: %v", err)
	}
	
	var result IP2Location
	if err := json.Unmarshal(body, &result); err != nil {
		return nil, fmt.Errorf("JSON解析失败: %v", err)
	}
	
	return &result, nil
}

// 方法3: 封装CLI输出为结构化数据
func GetIPLocationStructured(ip string) (*IP2Location, error) {
	output, err := GetIPLocationCLI(ip)
	if err != nil {
		return nil, err
	}
	
	var result IP2Location
	// 解析CLI的JSON输出
	if err := json.Unmarshal([]byte(output), &result); err != nil {
		return nil, fmt.Errorf("解析CLI输出失败: %v", err)
	}
	
	return &result, nil
}

// 示例:批量查询IP地址
func BatchIPLookup(ips []string, apiKey string) (map[string]*IP2Location, error) {
	results := make(map[string]*IP2Location)
	
	for _, ip := range ips {
		location, err := GetIPLocationAPI(ip, apiKey)
		if err != nil {
			fmt.Printf("IP %s 查询失败: %v\n", ip, err)
			continue
		}
		results[ip] = location
	}
	
	return results, nil
}

// 示例:生成简单报告
func GenerateReport(location *IP2Location) string {
	var report strings.Builder
	
	report.WriteString("=== IP地理位置报告 ===\n")
	report.WriteString(fmt.Sprintf("IP地址: %s\n", location.IP))
	report.WriteString(fmt.Sprintf("国家: %s (%s)\n", location.CountryName, location.CountryCode))
	report.WriteString(fmt.Sprintf("地区: %s\n", location.RegionName))
	report.WriteString(fmt.Sprintf("城市: %s\n", location.CityName))
	report.WriteString(fmt.Sprintf("坐标: %.6f, %.6f\n", location.Latitude, location.Longitude))
	report.WriteString(fmt.Sprintf("时区: %s\n", location.TimeZone))
	report.WriteString(fmt.Sprintf("ISP: %s\n", location.ISP))
	report.WriteString(fmt.Sprintf("代理检测: %v\n", location.Proxy.ProxyType != ""))
	
	if location.Proxy.ProxyType != "" {
		report.WriteString(fmt.Sprintf("代理类型: %s\n", location.Proxy.ProxyType))
		report.WriteString(fmt.Sprintf("VPN: %v\n", location.Proxy.IsVPN))
		report.WriteString(fmt.Sprintf("Tor: %v\n", location.Proxy.IsTor))
	}
	
	return report.String()
}

func main() {
	// 示例1: 使用CLI工具
	fmt.Println("=== 使用CLI工具查询 ===")
	cliResult, err := GetIPLocationCLI("8.8.8.8")
	if err != nil {
		fmt.Printf("错误: %v\n", err)
	} else {
		fmt.Println(cliResult)
	}
	
	// 示例2: 使用API查询(需要API密钥)
	fmt.Println("\n=== 使用API查询 ===")
	apiKey := os.Getenv("IP2LOCATION_API_KEY")
	if apiKey != "" {
		apiResult, err := GetIPLocationAPI("8.8.8.8", apiKey)
		if err != nil {
			fmt.Printf("错误: %v\n", err)
		} else {
			fmt.Printf("国家: %s\n", apiResult.CountryName)
			fmt.Printf("城市: %s\n", apiResult.CityName)
			fmt.Printf("ISP: %s\n", apiResult.ISP)
		}
		
		// 生成报告
		fmt.Println("\n=== 生成报告 ===")
		report := GenerateReport(apiResult)
		fmt.Println(report)
	}
	
	// 示例3: 批量查询
	fmt.Println("\n=== 批量查询示例 ===")
	ips := []string{"8.8.8.8", "1.1.1.1", "9.9.9.9"}
	if apiKey != "" {
		batchResults, _ := BatchIPLookup(ips, apiKey)
		for ip, result := range batchResults {
			fmt.Printf("%s -> %s, %s\n", ip, result.CountryName, result.CityName)
		}
	}
}

这个Go程序展示了三种使用IP2Location.io的方式:

  1. 直接调用CLI工具:通过exec.Command执行命令行工具
  2. API调用:直接调用IP2Location.io的REST API
  3. 结构化处理:将CLI输出解析为Go结构体

程序包含完整的数据结构定义,支持所有IP2Location.io返回的字段,包括代理检测、时区信息、移动网络数据等。GenerateReport函数展示了如何生成格式化的地理位置报告。

使用前需要:

  1. 安装IP2Location.io CLI工具
  2. 获取API密钥(用于API方式)
  3. 设置环境变量IP2LOCATION_API_KEY
回到顶部