Skip to content

Commit 49b7c9c

Browse files
committed
net/netip: make Prefix.MarshalText format 4-in-6 IPs consistently
Fixes #50115. Change-Id: Iac76e5b486d3a2a784583345eaeb22c31cc4a36d Reviewed-on: https://go-review.googlesource.com/c/go/+/371134 Trust: Matt Layher <[email protected]> Run-TryBot: Matt Layher <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]> Trust: Brad Fitzpatrick <[email protected]> TryBot-Result: Gopher Robot <[email protected]>
1 parent 5681704 commit 49b7c9c

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/net/netip/netip.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1422,7 +1422,12 @@ func (p Prefix) AppendTo(b []byte) []byte {
14221422
if p.ip.z == z4 {
14231423
b = p.ip.appendTo4(b)
14241424
} else {
1425-
b = p.ip.appendTo6(b)
1425+
if p.ip.Is4In6() {
1426+
b = append(b, "::ffff:"...)
1427+
b = p.ip.Unmap().appendTo4(b)
1428+
} else {
1429+
b = p.ip.appendTo6(b)
1430+
}
14261431
}
14271432

14281433
b = append(b, '/')

src/net/netip/netip_test.go

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,32 @@ func TestAddrPortMarshalUnmarshalBinary(t *testing.T) {
413413
}
414414
}
415415

416+
func TestPrefixMarshalTextString(t *testing.T) {
417+
tests := []struct {
418+
in Prefix
419+
want string
420+
}{
421+
{mustPrefix("1.2.3.4/24"), "1.2.3.4/24"},
422+
{mustPrefix("fd7a:115c:a1e0:ab12:4843:cd96:626b:430b/118"), "fd7a:115c:a1e0:ab12:4843:cd96:626b:430b/118"},
423+
{mustPrefix("::ffff:c000:0280/96"), "::ffff:192.0.2.128/96"},
424+
{mustPrefix("::ffff:c000:0280%eth0/37"), "::ffff:192.0.2.128/37"}, // Zone should be stripped
425+
{mustPrefix("::ffff:192.168.140.255/8"), "::ffff:192.168.140.255/8"},
426+
}
427+
for i, tt := range tests {
428+
if got := tt.in.String(); got != tt.want {
429+
t.Errorf("%d. for %v String = %q; want %q", i, tt.in, got, tt.want)
430+
}
431+
mt, err := tt.in.MarshalText()
432+
if err != nil {
433+
t.Errorf("%d. for %v MarshalText error: %v", i, tt.in, err)
434+
continue
435+
}
436+
if string(mt) != tt.want {
437+
t.Errorf("%d. for %v MarshalText = %q; want %q", i, tt.in, mt, tt.want)
438+
}
439+
}
440+
}
441+
416442
func TestPrefixMarshalUnmarshalBinary(t *testing.T) {
417443
type testCase struct {
418444
prefix Prefix
@@ -994,7 +1020,6 @@ func TestPrefixMarshalUnmarshal(t *testing.T) {
9941020
"0.0.0.0/0",
9951021
"::/0",
9961022
"::1/128",
997-
"::ffff:c000:1234/128",
9981023
"2001:db8::/32",
9991024
}
10001025

0 commit comments

Comments
 (0)