From f99a8ef3cf66ef61548a78a5a413557d5307a3fe Mon Sep 17 00:00:00 2001 From: dudaodong Date: Fri, 20 Sep 2024 19:29:31 +0800 Subject: [PATCH] refactoring: defect #247 --- netutil/net.go | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/netutil/net.go b/netutil/net.go index 6b6d090..767b5d1 100644 --- a/netutil/net.go +++ b/netutil/net.go @@ -21,21 +21,48 @@ import ( // GetInternalIp return internal ipv4. // Play: https://go.dev/play/p/5mbu-gFp7ei func GetInternalIp() string { - addr, err := net.InterfaceAddrs() + addrs, err := net.InterfaceAddrs() if err != nil { panic(err.Error()) } - for _, a := range addr { - if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() { - if ipNet.IP.To4() != nil { - return ipNet.IP.String() - } + + for _, addr := range addrs { + var ip net.IP + switch v := addr.(type) { + case *net.IPNet: + ip = v.IP + case *net.IPAddr: + ip = v.IP + } + + if ip != nil && (ip.IsLinkLocalUnicast() || ip.IsGlobalUnicast()) { + continue + } + + if ipv4 := ip.To4(); ipv4 != nil { + return ipv4.String() } } return "" } +// func GetInternalIp() string { +// addr, err := net.InterfaceAddrs() +// if err != nil { +// panic(err.Error()) +// } +// for _, a := range addr { +// if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() { +// if ipNet.IP.To4() != nil { +// return ipNet.IP.String() +// } +// } +// } + +// return "" +// } + // GetRequestPublicIp return the requested public ip. // Play: https://go.dev/play/p/kxU-YDc_eBo func GetRequestPublicIp(req *http.Request) string {