Skip to content

Commit

Permalink
Merge e37cb12 into 189cbde
Browse files Browse the repository at this point in the history
  • Loading branch information
kozlovic committed Jan 17, 2019
2 parents 189cbde + e37cb12 commit 8a82114
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
13 changes: 13 additions & 0 deletions nats.go
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
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 8a82114

Please sign in to comment.