package monitoring import ( "context" "io" "log" "net" "net/http" "regexp" "time" "github.com/komari-monitor/komari-agent/dnsresolver" ) var ( // 创建适用于IPv4和IPv6的HTTP客户端 ipv4HTTPClient = &http.Client{ Transport: &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { dialer := dnsresolver.GetNetDialer(15 * time.Second) return dialer.DialContext(ctx, "tcp4", addr) // 锁v4防止出现问题 }, MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }, Timeout: 15 * time.Second, } ipv6HTTPClient = &http.Client{ Transport: &http.Transport{ DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { dialer := dnsresolver.GetNetDialer(15 * time.Second) return dialer.DialContext(ctx, "tcp6", addr) // 锁v6防止出现问题 }, MaxIdleConns: 10, IdleConnTimeout: 30 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }, Timeout: 15 * time.Second, } userAgent = "curl/8.0.1" ) func GetIPv4Address() (string, error) { webAPIs := []string{ "https://www.visa.cn/cdn-cgi/trace", "https://www.qualcomm.cn/cdn-cgi/trace", "https://www.toutiao.com/stream/widget/local_weather/data/", "https://edge-ip.html.zone/geo", "https://vercel-ip.html.zone/geo", "http://ipv4.ip.sb", "https://api.ipify.org?format=json", } for _, api := range webAPIs { // get ipv4 req, err := http.NewRequest("GET", api, nil) if err != nil { continue } req.Header.Set("User-Agent", userAgent) resp, err := ipv4HTTPClient.Do(req) if err != nil { continue } body, err := io.ReadAll(resp.Body) _ = resp.Body.Close() // 获取后立即关闭防止堵塞 if err != nil { continue } re := regexp.MustCompile(`\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}`) ipv4 := re.FindString(string(body)) if ipv4 != "" { log.Printf("Get IPV4 Success: %s", ipv4) return ipv4, nil } } return "", nil } func GetIPv6Address() (string, error) { webAPIs := []string{ "https://v6.ip.zxinc.org/info.php?type=json", "https://api6.ipify.org?format=json", "https://ipv6.icanhazip.com", "https://api-ipv6.ip.sb/geoip", } for _, api := range webAPIs { // get ipv6 req, err := http.NewRequest("GET", api, nil) if err != nil { continue } req.Header.Set("User-Agent", userAgent) resp, err := ipv6HTTPClient.Do(req) if err != nil { continue } body, err := io.ReadAll(resp.Body) _ = resp.Body.Close() // 获取后立即关闭防止堵塞 if err != nil { continue } // 使用正则表达式从响应体中提取IPv6地址 re := regexp.MustCompile(`(([0-9A-Fa-f]{1,4}:){7})([0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,6}:)(([0-9A-Fa-f]{1,4}:){0,4})([0-9A-Fa-f]{0,4})`) ipv6 := re.FindString(string(body)) if ipv6 != "" { log.Printf("Get IPV6 Success: %s", ipv6) return ipv6, nil } } return "", nil } func GetIPAddress() (ipv4, ipv6 string, err error) { ipv4, err = GetIPv4Address() if err != nil { log.Printf("Get IPV4 Error: %v", err) ipv4 = "" } ipv6, err = GetIPv6Address() if err != nil { log.Printf("Get IPV6 Error: %v", err) ipv6 = "" } return ipv4, ipv6, nil }