使用go dns

This commit is contained in:
2025-06-10 09:08:54 +08:00
parent 28aae5cec3
commit 851b643374
3 changed files with 16 additions and 8 deletions

View File

@@ -3,31 +3,32 @@ package main
import (
"fmt"
"io"
"net"
"net/http"
"strings"
)
func GetLocalIpv4Addr() string {
// 发送 HTTP GET 请求到外部服务
resp, err := http.Get("https://inet-ip.aixiao.me/")
if err != nil {
fmt.Printf("请求失败: %s\n", err)
return "NULL"
}
defer resp.Body.Close() // 确保响应体在函数结束时关闭
defer resp.Body.Close()
// 读取响应体内容
ip, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Printf("读取响应失败: %s\n", err)
return "NULL"
}
// 去除字符串末尾的换行符
ipStr := strings.TrimRight(string(ip), "\n")
// 输出获取到的公网 IP
fmt.Printf("%s %d\n", ipStr, len(ipStr))
ipStr := strings.TrimSpace(string(ip))
// ✅ 验证是否是合法 IPv4
if net.ParseIP(ipStr) == nil || strings.Contains(ipStr, "<") {
fmt.Printf("无效的IP响应: %q\n", ipStr)
return "NULL"
}
fmt.Printf("公网IP: %s\n", ipStr)
return ipStr
}