Skip to content

Commit

Permalink
Merge pull request #426 from nats-io/add_connected_addr
Browse files Browse the repository at this point in the history
[ADDED] Conn.ConnectedAddr()
  • Loading branch information
kozlovic authored Jan 17, 2019
2 parents 189cbde + e37cb12 commit abeb2b1
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 abeb2b1

Please sign in to comment.