This commit is contained in:
xxj
2026-02-28 15:26:51 +08:00
parent 6f7ba42fba
commit 9aec6824e7
2 changed files with 25 additions and 1 deletions
+7 -1
View File
@@ -31,9 +31,15 @@ func GetLocalIP() (ip string) {
mylog.Error(err)
return
}
// 定义链路本地地址范围(169.254.0.0/16
_, linkLocal, err := net.ParseCIDR("169.254.0.0/16")
if err != nil {
mylog.Error(err)
return
}
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
if ipnet.IP.To4() != nil && !linkLocal.Contains(ipnet.IP) {
ip = ipnet.IP.String()
break
}
+18
View File
@@ -0,0 +1,18 @@
package tools
import (
"testing"
)
func TestGetLocalIP(t *testing.T) {
ip := GetLocalIP()
t.Logf("Local IP: %s", ip)
// 验证IP不为空且不是链路本地地址
if ip == "" {
t.Error("GetLocalIP returned empty string")
}
// 验证IP不是169.254开头的链路本地地址
if len(ip) >= 7 && ip[:7] == "169.254" {
t.Errorf("GetLocalIP returned link-local address: %s", ip)
}
}