diff --git a/nats.go b/nats.go index dffaf3e6e..41272488f 100644 --- a/nats.go +++ b/nats.go @@ -1280,6 +1280,19 @@ func (nc *Conn) ConnectedUrl() string { return nc.current.url.String() } +// ConnectedAddr returns the connected server's IP +func (nc *Conn) ConnectedAddr() string { + if nc == nil { + return _EMPTY_ + } + nc.mu.Lock() + defer nc.mu.Unlock() + if nc.status != CONNECTED { + return _EMPTY_ + } + return nc.conn.RemoteAddr().String() +} + // Report the connected server's Id func (nc *Conn) ConnectedServerId() string { if nc == nil { diff --git a/nats_test.go b/nats_test.go index 626920a31..c84783dfe 100644 --- a/nats_test.go +++ b/nats_test.go @@ -1592,3 +1592,25 @@ func TestLookupHostResultIsRandomized(t *testing.T) { } t.Fatalf("Always used first address returned by LookupHost") } + +func TestConnectedAddr(t *testing.T) { + s := RunServerOnPort(TEST_PORT) + defer s.Shutdown() + + var nc *Conn + if addr := nc.ConnectedAddr(); addr != _EMPTY_ { + t.Fatalf("Expected empty result for nil connection, got %q", addr) + } + nc, err := Connect(fmt.Sprintf("localhost:%d", TEST_PORT)) + if err != nil { + t.Fatalf("Error connecting: %v", err) + } + expected := s.Addr().String() + if addr := nc.ConnectedAddr(); addr != expected { + t.Fatalf("Expected address %q, got %q", expected, addr) + } + nc.Close() + if addr := nc.ConnectedAddr(); addr != _EMPTY_ { + t.Fatalf("Expected empty result for closed connection, got %q", addr) + } +}