From 20768b72c35851f0ebf5d1fa658fc6450fbd9743 Mon Sep 17 00:00:00 2001 From: Ivan Kozlovic Date: Wed, 22 Jan 2020 08:59:43 -0700 Subject: [PATCH] [FIXED] Display of connections address when using IPv6 When the server logs information related to a connection, it uses the connection IP and remote port as a prefix. When it was an IPv6 address, the square brackets would be missing. Signed-off-by: Ivan Kozlovic --- server/client.go | 9 +++++---- server/client_test.go | 22 ++++++++++++++++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/server/client.go b/server/client.go index 40535d83..5e9ec94f 100644 --- a/server/client.go +++ b/server/client.go @@ -23,6 +23,7 @@ import ( "net" "regexp" "runtime" + "strconv" "strings" "sync" "sync/atomic" @@ -465,10 +466,10 @@ func (c *client) initClient() { // snapshot the string version of the connection var conn string if ip, ok := c.nc.(*net.TCPConn); ok { - addr := ip.RemoteAddr().(*net.TCPAddr) - c.host = addr.IP.String() - c.port = uint16(addr.Port) - conn = fmt.Sprintf("%s:%d", addr.IP, addr.Port) + conn = ip.RemoteAddr().String() + host, port, _ := net.SplitHostPort(conn) + iPort, _ := strconv.Atoi(port) + c.host, c.port = host, uint16(iPort) } switch c.kind { diff --git a/server/client_test.go b/server/client_test.go index 1a2d486c..80de55f7 100644 --- a/server/client_test.go +++ b/server/client_test.go @@ -1893,3 +1893,25 @@ func TestClientStalledDuration(t *testing.T) { }) } } + +func TestClientIPv6Address(t *testing.T) { + opts := DefaultOptions() + opts.Host = "0.0.0.0" + s := RunServer(opts) + defer s.Shutdown() + + nc, err := nats.Connect(fmt.Sprintf("nats://[::1]:%v", opts.Port)) + // Travis may not accept IPv6, in that case, skip the test. + if err != nil { + t.Skipf("Skipping test because could not connect: %v", err) + } + defer nc.Close() + + c := s.GetClient(1) + c.mu.Lock() + ncs := c.ncs + c.mu.Unlock() + if !strings.HasPrefix(ncs, "[::1]") { + t.Fatalf("Wrong string representation of an IPv6 address: %q", ncs) + } +}