github.com/searKing/golang/go@v1.2.117/net/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 net_test 6 7 import ( 8 "fmt" 9 "net" 10 "reflect" 11 "testing" 12 13 net_ "github.com/searKing/golang/go/net" 14 ) 15 16 var parseIPTests = []struct { 17 ipIntStr string 18 base int 19 ip net.IP 20 ipFmtStr string 21 }{ 22 {ipIntStr: "2130706690", base: 10, ipFmtStr: "127.0.1.2", ip: net.IPv4(127, 0, 1, 2)}, 23 {ipIntStr: "2130706433", base: 10, ipFmtStr: "127.0.0.1", ip: net.IPv4(127, 0, 0, 1)}, 24 {ipIntStr: "2130772483", base: 10, ipFmtStr: "127.001.002.003", ip: net.IPv4(127, 1, 2, 3)}, 25 {ipIntStr: "2130772483", base: 10, ipFmtStr: "::ffff:127.1.2.3", ip: net.IPv4(127, 1, 2, 3)}, 26 {ipIntStr: "2130772483", base: 10, ipFmtStr: "::ffff:127.001.002.003", ip: net.IPv4(127, 1, 2, 3)}, 27 {ipIntStr: "2130772483", base: 10, ipFmtStr: "::ffff:7f01:0203", ip: net.IPv4(127, 1, 2, 3)}, 28 {ipIntStr: "2130772483", base: 10, ipFmtStr: "0:0:0:0:0000:ffff:127.1.2.3", ip: net.IPv4(127, 1, 2, 3)}, 29 {ipIntStr: "2130772483", base: 10, ipFmtStr: "0:0:0:0:000000:ffff:127.1.2.3", ip: net.IPv4(127, 1, 2, 3)}, 30 {ipIntStr: "2130772483", base: 10, ipFmtStr: "0:0:0:0::ffff:127.1.2.3", ip: net.IPv4(127, 1, 2, 3)}, 31 32 {ipIntStr: "20014860000020010000000000000068", base: 16, ipFmtStr: "2001:4860:0:2001::68", ip: net.IP{0x20, 0x01, 0x48, 0x60, 0, 0, 0x20, 0x01, 0, 0, 0, 0, 0, 0, 0x00, 0x68}}, 33 {ipIntStr: "20014860000020010000000000000068", base: 16, ipFmtStr: "2001:4860:0000:2001:0000:0000:0000:0068", ip: net.IP{0x20, 0x01, 0x48, 0x60, 0, 0, 0x20, 0x01, 0, 0, 0, 0, 0, 0, 0x00, 0x68}}, 34 } 35 36 func TestParseIPV6(t *testing.T) { 37 for i, tt := range parseIPTests { 38 if got := net_.ParseIPV6(tt.ipIntStr, tt.base); !reflect.DeepEqual(got, tt.ip) { 39 t.Errorf("#%d, ParseIP(%s) = %v, want %v, %s", i, tt.ipIntStr, got, tt.ip, tt.ipFmtStr) 40 } 41 } 42 } 43 44 func TestIPtoInt64(t *testing.T) { 45 for i, tt := range parseIPTests { 46 got := net_.IPtoBigInt(tt.ip) 47 var format string 48 switch tt.base { 49 case 2: 50 format = "%b" 51 case 8: 52 format = "%o" 53 case 16: 54 format = "%x" 55 default: 56 format = "%d" 57 } 58 gotString := fmt.Sprintf(format, got) 59 60 if gotString != tt.ipIntStr { 61 t.Errorf("#%d, IPtoBigInt(%s) = %d, want %s", i, tt.ip.String(), got, tt.ipIntStr) 62 } 63 } 64 } 65 66 func TestIPFormat_Format(t *testing.T) { 67 for i, tt := range parseIPTests { 68 var format string 69 switch tt.base { 70 case 2: 71 format = "%b" 72 case 8: 73 format = "%o" 74 case 16: 75 format = "%x" 76 default: 77 format = "%d" 78 } 79 gotString := fmt.Sprintf(format, net_.IPFormat(tt.ip)) 80 81 if gotString != tt.ipIntStr { 82 t.Errorf("#%d, fmt.Sprintf(%q) = %s, want %s", i, format, gotString, tt.ipIntStr) 83 } 84 } 85 }