Merge pull request #1877 from alexbozhenko/expose_local_addr

Add nc.LocalAddr, similar to nc.ConnectedAddr
This commit is contained in:
Waldemar Quevedo
2025-05-27 18:09:08 -07:00
committed by GitHub
2 changed files with 48 additions and 0 deletions

15
nats.go
View File

@@ -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 {

View File

@@ -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()