mirror of
https://github.com/xxjwxc/public.git
synced 2026-04-22 15:07:48 +08:00
1
This commit is contained in:
+7
-1
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user