From e94bf49362a714350afb50536dcda5b7f5811ee9 Mon Sep 17 00:00:00 2001 From: KallyDev <36319157+kallydev@users.noreply.github.com> Date: Tue, 13 Jul 2021 13:04:34 +0800 Subject: [PATCH] fix: filter lookback interface for utils.ClientIP (#700) --- internal/utils/net.go | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/internal/utils/net.go b/internal/utils/net.go index 0dfcff82..cf35594b 100644 --- a/internal/utils/net.go +++ b/internal/utils/net.go @@ -40,14 +40,19 @@ func init() { } func ClientIP4() ([]byte, error) { - addrs, err := net.InterfaceAddrs() - if err != nil { - return nil, errors.New("unexpected IP address") - } - for _, addr := range addrs { - if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { - if ip4 := ipnet.IP.To4(); ip4 != nil { - return ip4, nil + if ifaces, err := net.Interfaces(); err == nil && ifaces != nil { + for _, iface := range ifaces { + if iface.Flags&net.FlagLoopback != 0 || iface.Flags&net.FlagUp == 0 { + continue + } + if addrs, err := iface.Addrs(); err == nil && addrs != nil { + for _, addr := range addrs { + if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { + if ip4 := ipnet.IP.To4(); ip4 != nil { + return ip4, nil + } + } + } } } }