34 lines
654 B
Go
34 lines
654 B
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"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() // 确保响应体在函数结束时关闭
|
|
|
|
// 读取响应体内容
|
|
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))
|
|
|
|
return ipStr
|
|
}
|