mirror of
https://github.com/nats-io/nats.go.git
synced 2025-09-26 20:41:41 +08:00
Merge pull request #1877 from alexbozhenko/expose_local_addr
Add nc.LocalAddr, similar to nc.ConnectedAddr
This commit is contained in:
15
nats.go
15
nats.go
@@ -2292,6 +2292,21 @@ func (nc *Conn) ConnectedAddr() string {
|
||||
return nc.conn.RemoteAddr().String()
|
||||
}
|
||||
|
||||
// LocalAddr returns the local network address of the connection
|
||||
func (nc *Conn) LocalAddr() string {
|
||||
if nc == nil {
|
||||
return _EMPTY_
|
||||
}
|
||||
|
||||
nc.mu.RLock()
|
||||
defer nc.mu.RUnlock()
|
||||
|
||||
if nc.status != CONNECTED {
|
||||
return _EMPTY_
|
||||
}
|
||||
return nc.conn.LocalAddr().String()
|
||||
}
|
||||
|
||||
// ConnectedServerId reports the connected server's Id
|
||||
func (nc *Conn) ConnectedServerId() string {
|
||||
if nc == nil {
|
||||
|
@@ -553,6 +553,39 @@ func TestConnectedAddr(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalAddr(t *testing.T) {
|
||||
s := RunServerOnPort(TEST_PORT)
|
||||
defer s.Shutdown()
|
||||
|
||||
var nc *nats.Conn
|
||||
if addr := nc.LocalAddr(); addr != "" {
|
||||
t.Fatalf("Expected empty result for nil connection, got %q", addr)
|
||||
}
|
||||
nc, err := nats.Connect(fmt.Sprintf("localhost:%d", TEST_PORT))
|
||||
if err != nil {
|
||||
t.Fatalf("Error connecting: %v", err)
|
||||
}
|
||||
addr := nc.LocalAddr()
|
||||
if addr == "" {
|
||||
t.Fatalf("Expected non-empty local address")
|
||||
}
|
||||
// Verify it's a valid address format
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
t.Fatalf("Expected valid host:port format, got %q: %v", addr, err)
|
||||
}
|
||||
if host == "" {
|
||||
t.Fatalf("Expected non-empty host in address %q", addr)
|
||||
}
|
||||
if port == "" {
|
||||
t.Fatalf("Expected non-empty port in address %q", addr)
|
||||
}
|
||||
nc.Close()
|
||||
if addr := nc.LocalAddr(); addr != "" {
|
||||
t.Fatalf("Expected empty result for closed connection, got %q", addr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSubscribeSyncRace(t *testing.T) {
|
||||
s := RunServerOnPort(TEST_PORT)
|
||||
defer s.Shutdown()
|
||||
|
Reference in New Issue
Block a user