From e176ddfcdd29b5881fd23a9394c52dec002d27d6 Mon Sep 17 00:00:00 2001 From: hshe Date: Wed, 7 Sep 2022 11:43:55 +0800 Subject: [PATCH] feat(internal/host): prefer ipv4 than ipv6 (#2342) * feat:prefer ipv4 than ipv6 * feat:prefer ipv4 than ipv6 * feat:prefer ipv4 than ipv6 * feat:prefer ipv4 than ipv6 --- internal/host/host.go | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/internal/host/host.go b/internal/host/host.go index bf204eede..774f7ae37 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -51,19 +51,19 @@ func Extract(hostPort string, lis net.Listener) (string, error) { return "", err } minIndex := int(^uint(0) >> 1) - var result net.IP + ips := make([]net.IP, 0) for _, iface := range ifaces { if (iface.Flags & net.FlagUp) == 0 { continue } - if iface.Index >= minIndex && result != nil { + if iface.Index >= minIndex && len(ips) != 0 { continue } addrs, err := iface.Addrs() if err != nil { continue } - for _, rawAddr := range addrs { + for i, rawAddr := range addrs { var ip net.IP switch addr := rawAddr.(type) { case *net.IPAddr: @@ -75,13 +75,18 @@ func Extract(hostPort string, lis net.Listener) (string, error) { } if isValidIP(ip.String()) { minIndex = iface.Index - result = ip - break + if i == 0 { + ips = make([]net.IP, 0, 1) + } + ips = append(ips, ip) + if ip.To4() != nil { + break + } } } } - if result != nil { - return net.JoinHostPort(result.String(), port), nil + if len(ips) != 0 { + return net.JoinHostPort(ips[len(ips)-1].String(), port), nil } return "", nil }