github.com/searKing/golang/go@v1.2.117/net/addr/local_ip_test.go (about) 1 // Copyright 2021 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package addr_test 6 7 import ( 8 "net" 9 "testing" 10 11 "github.com/searKing/golang/go/net/addr" 12 ) 13 14 func TestScoreAddr(t *testing.T) { 15 ipv4 := net.ParseIP("10.0.1.2") 16 ipv6 := net.ParseIP("2001:db8:a0b:12f0::1") 17 18 tests := []struct { 19 msg string 20 iface net.Interface 21 addr net.Addr 22 wantScore int 23 wantIP net.IP 24 }{ 25 { 26 msg: "non-local up ipv4 IPNet address", 27 iface: net.Interface{Flags: net.FlagUp}, 28 addr: &net.IPNet{IP: ipv4}, 29 wantScore: 475, 30 wantIP: ipv4, 31 }, 32 { 33 msg: "non-local up ipv4 IPAddr address", 34 iface: net.Interface{Flags: net.FlagUp}, 35 addr: &net.IPAddr{IP: ipv4}, 36 wantScore: 475, 37 wantIP: ipv4, 38 }, 39 { 40 msg: "non-local up ipv4 IPAddr address, docker interface", 41 iface: net.Interface{ 42 Flags: net.FlagUp, 43 HardwareAddr: mustParseMAC("02:42:ac:11:56:af"), 44 }, 45 addr: &net.IPNet{IP: ipv4}, 46 wantScore: 425, 47 wantIP: ipv4, 48 }, 49 { 50 msg: "non-local up ipv4 address, local MAC address", 51 iface: net.Interface{ 52 Flags: net.FlagUp, 53 HardwareAddr: mustParseMAC("02:42:9c:52:fc:86"), 54 }, 55 addr: &net.IPNet{IP: ipv4}, 56 wantScore: 425, 57 wantIP: ipv4, 58 }, 59 { 60 msg: "non-local down ipv4 address", 61 iface: net.Interface{}, 62 addr: &net.IPNet{IP: ipv4}, 63 wantScore: 375, 64 wantIP: ipv4, 65 }, 66 { 67 msg: "non-local down ipv6 address", 68 iface: net.Interface{}, 69 addr: &net.IPAddr{IP: ipv6}, 70 wantScore: 75, 71 wantIP: ipv6, 72 }, 73 { 74 msg: "unknown address type", 75 iface: net.Interface{}, 76 addr: &net.UnixAddr{Name: "/tmp/socket"}, 77 wantScore: -1, 78 }, 79 } 80 81 for i, tt := range tests { 82 gotScore, gotIP := addr.ScoreAddr(tt.iface, tt.addr) 83 if tt.wantScore != gotScore { 84 t.Errorf("#%d, %s: expected %d got %d", i, tt.msg, tt.wantScore, gotScore) 85 } 86 if tt.wantIP.String() != gotIP.String() { 87 t.Errorf("#%d, %s: expected %q got %q", i, tt.msg, tt.wantIP, gotIP) 88 } 89 } 90 } 91 92 func mustParseMAC(s string) net.HardwareAddr { 93 addr, err := net.ParseMAC(s) 94 if err != nil { 95 panic(err) 96 } 97 return addr 98 }