Skip to content

Add nc.LocalAddr, similar to nc.ConnectedAddr #1877

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions nats.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
33 changes: 33 additions & 0 deletions test/nats_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down