Skip to content

Commit 9c6e8f6

Browse files
committed
net/netip: make AddrPort.MarshalText format 4-in-6 IPs consistently
Thanks again to @capnspacehook. Fixes #50110 Change-Id: I1973bdea68eac9842b45f9524f62152e4f5342cf Reviewed-on: https://go-review.googlesource.com/c/go/+/371114 Run-TryBot: Brad Fitzpatrick <[email protected]> Reviewed-by: Matt Layher <[email protected]> Trust: Matt Layher <[email protected]> Trust: Brad Fitzpatrick <[email protected]> TryBot-Result: Gopher Robot <[email protected]>
1 parent 1c1998e commit 9c6e8f6

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

src/net/netip/netip.go

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1157,8 +1157,17 @@ func (p AddrPort) AppendTo(b []byte) []byte {
11571157
case z4:
11581158
b = p.ip.appendTo4(b)
11591159
default:
1160-
b = append(b, '[')
1161-
b = p.ip.appendTo6(b)
1160+
if p.ip.Is4In6() {
1161+
b = append(b, "[::ffff:"...)
1162+
b = p.ip.Unmap().appendTo4(b)
1163+
if z := p.ip.Zone(); z != "" {
1164+
b = append(b, '%')
1165+
b = append(b, z...)
1166+
}
1167+
} else {
1168+
b = append(b, '[')
1169+
b = p.ip.appendTo6(b)
1170+
}
11621171
b = append(b, ']')
11631172
}
11641173
b = append(b, ':')

src/net/netip/netip_test.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,6 +347,32 @@ func TestAddrMarshalUnmarshalBinary(t *testing.T) {
347347
}
348348
}
349349

350+
func TestAddrPortMarshalTextString(t *testing.T) {
351+
tests := []struct {
352+
in AddrPort
353+
want string
354+
}{
355+
{mustIPPort("1.2.3.4:80"), "1.2.3.4:80"},
356+
{mustIPPort("[1::CAFE]:80"), "[1::cafe]:80"},
357+
{mustIPPort("[1::CAFE%en0]:80"), "[1::cafe%en0]:80"},
358+
{mustIPPort("[::FFFF:192.168.140.255]:80"), "[::ffff:192.168.140.255]:80"},
359+
{mustIPPort("[::FFFF:192.168.140.255%en0]:80"), "[::ffff:192.168.140.255%en0]:80"},
360+
}
361+
for i, tt := range tests {
362+
if got := tt.in.String(); got != tt.want {
363+
t.Errorf("%d. for (%v, %v) String = %q; want %q", i, tt.in.Addr(), tt.in.Port(), got, tt.want)
364+
}
365+
mt, err := tt.in.MarshalText()
366+
if err != nil {
367+
t.Errorf("%d. for (%v, %v) MarshalText error: %v", i, tt.in.Addr(), tt.in.Port(), err)
368+
continue
369+
}
370+
if string(mt) != tt.want {
371+
t.Errorf("%d. for (%v, %v) MarshalText = %q; want %q", i, tt.in.Addr(), tt.in.Port(), mt, tt.want)
372+
}
373+
}
374+
}
375+
350376
func TestAddrPortMarshalUnmarshalBinary(t *testing.T) {
351377
tests := []struct {
352378
ipport string

0 commit comments

Comments
 (0)