Skip to content

Commit

Permalink
[ADDED] Conn.ConnectedAddr()
Browse files Browse the repository at this point in the history
This returns the RemoteAddr().String() of the server the connection
is currently connected to.
That is, say server is running on loopback port 4222, this call
would return: "127.0.0.1:4222"

Signed-off-by: Ivan Kozlovic <[email protected]>
  • Loading branch information
kozlovic committed Jan 17, 2019
1 parent 189cbde commit e37cb12
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions nats.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
22 changes: 22 additions & 0 deletions nats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit e37cb12

Please sign in to comment.