浏览代码

fix HostAddress generation

Jonathan Turner 7 年之前
父节点
当前提交
f0f111413e
共有 2 个文件被更改,包括 32 次插入5 次删除
  1. 3 5
      types/HostAddress.go
  2. 29 0
      types/HostAddress_test.go

+ 3 - 5
types/HostAddress.go

@@ -53,21 +53,19 @@ func GetHostAddress(s string) (HostAddress, error) {
 		return h, fmt.Errorf("invalid format of client address: %v", err)
 	}
 	ip := net.ParseIP(cAddr)
-	hb, err := ip.MarshalText()
-	if err != nil {
-		return h, fmt.Errorf("could not marshal client's address into bytes: %v", err)
-	}
 	var ht int32
 	if ip.To4() != nil {
 		ht = addrtype.IPv4
+		ip = ip.To4()
 	} else if ip.To16() != nil {
 		ht = addrtype.IPv6
+		ip = ip.To16()
 	} else {
 		return h, fmt.Errorf("could not determine client's address types: %v", err)
 	}
 	h = HostAddress{
 		AddrType: ht,
-		Address:  hb,
+		Address:  ip,
 	}
 	return h, nil
 }

+ 29 - 0
types/HostAddress_test.go

@@ -0,0 +1,29 @@
+package types
+
+import (
+	"encoding/hex"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+	"gopkg.in/jcmturner/gokrb5.v6/iana/addrtype"
+)
+
+func TestGetHostAddress(t *testing.T) {
+	tests := []struct {
+		str    string
+		ipType int32
+		hex    string
+	}{
+		{"192.168.1.100", addrtype.IPv4, "c0a80164"},
+		{"127.0.0.1", addrtype.IPv4, "7f000001"},
+		{"[fe80::1cf3:b43b:df29:d43e]", addrtype.IPv6, "fe800000000000001cf3b43bdf29d43e"},
+	}
+	for _, test := range tests {
+		h, err := GetHostAddress(test.str + ":1234")
+		if err != nil {
+			t.Errorf("error getting host for %s: %v", test.str, err)
+		}
+		assert.Equal(t, test.ipType, h.AddrType, "wrong address type for %s", test.str)
+		assert.Equal(t, test.hex, hex.EncodeToString(h.Address), "wrong address bytes for %s", test.str)
+	}
+}