From 7aa9f352f8dfecdde655849963db2f11c62d7cf5 Mon Sep 17 00:00:00 2001 From: hshe <hshe@163.com> Date: Thu, 16 Dec 2021 22:41:44 +0800 Subject: [PATCH] =?UTF-8?q?fix:internal/host:=E9=80=89=E6=8B=A9ip=E6=9C=AA?= =?UTF-8?q?=E5=88=A4=E6=96=ADip=E6=98=AF=E5=90=A6=E5=8F=AF=E7=94=A8&&?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E5=BA=8F=E5=8F=B7=E6=9C=80=E5=B0=8F=E7=9A=84?= =?UTF-8?q?ip(#1686)=20(#1687)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/host/host.go | 15 ++++++++++++++- internal/host/host_test.go | 10 ++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/internal/host/host.go b/internal/host/host.go index ac0cf2121..078660be5 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -53,7 +53,17 @@ func Extract(hostPort string, lis net.Listener) (string, error) { if err != nil { return "", err } + lowest := int(^uint(0) >> 1) + var result net.IP for _, iface := range ifaces { + if (iface.Flags & net.FlagUp) == 0 { + continue + } + if iface.Index < lowest || result == nil { + lowest = iface.Index + } else if result != nil { + continue + } addrs, err := iface.Addrs() if err != nil { continue @@ -69,9 +79,12 @@ func Extract(hostPort string, lis net.Listener) (string, error) { continue } if isValidIP(ip.String()) { - return net.JoinHostPort(ip.String(), port), nil + result = ip } } } + if result != nil { + return net.JoinHostPort(result.String(), port), nil + } return "", nil } diff --git a/internal/host/host_test.go b/internal/host/host_test.go index 102be6515..e383ec371 100644 --- a/internal/host/host_test.go +++ b/internal/host/host_test.go @@ -128,3 +128,13 @@ func TestExtractHostPort(t *testing.T) { } t.Logf("host port: %s, %d", host, port) } + +func TestIpIsUp(t *testing.T) { + interfaces, err := net.Interfaces() + if err != nil { + t.Fail() + } + for i := range interfaces { + println(interfaces[i].Name, interfaces[i].Flags&net.FlagUp) + } +}