From 49b7c9caec6b96d0b327624efee61bd8a72cf68c Mon Sep 17 00:00:00 2001 From: Matt Layher Date: Sun, 12 Dec 2021 10:53:17 -0500 Subject: [PATCH] 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 Run-TryBot: Matt Layher Reviewed-by: Brad Fitzpatrick Trust: Brad Fitzpatrick TryBot-Result: Gopher Robot --- src/net/netip/netip.go | 7 ++++++- src/net/netip/netip_test.go | 27 ++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/src/net/netip/netip.go b/src/net/netip/netip.go index aaaf435ed8e..591d38abc89 100644 --- a/src/net/netip/netip.go +++ b/src/net/netip/netip.go @@ -1422,7 +1422,12 @@ func (p Prefix) AppendTo(b []byte) []byte { if p.ip.z == z4 { b = p.ip.appendTo4(b) } else { - b = p.ip.appendTo6(b) + if p.ip.Is4In6() { + b = append(b, "::ffff:"...) + b = p.ip.Unmap().appendTo4(b) + } else { + b = p.ip.appendTo6(b) + } } b = append(b, '/') diff --git a/src/net/netip/netip_test.go b/src/net/netip/netip_test.go index 869628050a8..520695cdfb8 100644 --- a/src/net/netip/netip_test.go +++ b/src/net/netip/netip_test.go @@ -413,6 +413,32 @@ func TestAddrPortMarshalUnmarshalBinary(t *testing.T) { } } +func TestPrefixMarshalTextString(t *testing.T) { + tests := []struct { + in Prefix + want string + }{ + {mustPrefix("1.2.3.4/24"), "1.2.3.4/24"}, + {mustPrefix("fd7a:115c:a1e0:ab12:4843:cd96:626b:430b/118"), "fd7a:115c:a1e0:ab12:4843:cd96:626b:430b/118"}, + {mustPrefix("::ffff:c000:0280/96"), "::ffff:192.0.2.128/96"}, + {mustPrefix("::ffff:c000:0280%eth0/37"), "::ffff:192.0.2.128/37"}, // Zone should be stripped + {mustPrefix("::ffff:192.168.140.255/8"), "::ffff:192.168.140.255/8"}, + } + for i, tt := range tests { + if got := tt.in.String(); got != tt.want { + t.Errorf("%d. for %v String = %q; want %q", i, tt.in, got, tt.want) + } + mt, err := tt.in.MarshalText() + if err != nil { + t.Errorf("%d. for %v MarshalText error: %v", i, tt.in, err) + continue + } + if string(mt) != tt.want { + t.Errorf("%d. for %v MarshalText = %q; want %q", i, tt.in, mt, tt.want) + } + } +} + func TestPrefixMarshalUnmarshalBinary(t *testing.T) { type testCase struct { prefix Prefix @@ -994,7 +1020,6 @@ func TestPrefixMarshalUnmarshal(t *testing.T) { "0.0.0.0/0", "::/0", "::1/128", - "::ffff:c000:1234/128", "2001:db8::/32", }