Skip to content

Commit abad5e6

Browse files
authored
Merge pull request #1877 from alexbozhenko/expose_local_addr
Add nc.LocalAddr, similar to nc.ConnectedAddr
2 parents 70300b2 + 2ea3acc commit abad5e6

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

nats.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2292,6 +2292,21 @@ func (nc *Conn) ConnectedAddr() string {
22922292
return nc.conn.RemoteAddr().String()
22932293
}
22942294

2295+
// LocalAddr returns the local network address of the connection
2296+
func (nc *Conn) LocalAddr() string {
2297+
if nc == nil {
2298+
return _EMPTY_
2299+
}
2300+
2301+
nc.mu.RLock()
2302+
defer nc.mu.RUnlock()
2303+
2304+
if nc.status != CONNECTED {
2305+
return _EMPTY_
2306+
}
2307+
return nc.conn.LocalAddr().String()
2308+
}
2309+
22952310
// ConnectedServerId reports the connected server's Id
22962311
func (nc *Conn) ConnectedServerId() string {
22972312
if nc == nil {

test/nats_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,39 @@ func TestConnectedAddr(t *testing.T) {
553553
}
554554
}
555555

556+
func TestLocalAddr(t *testing.T) {
557+
s := RunServerOnPort(TEST_PORT)
558+
defer s.Shutdown()
559+
560+
var nc *nats.Conn
561+
if addr := nc.LocalAddr(); addr != "" {
562+
t.Fatalf("Expected empty result for nil connection, got %q", addr)
563+
}
564+
nc, err := nats.Connect(fmt.Sprintf("localhost:%d", TEST_PORT))
565+
if err != nil {
566+
t.Fatalf("Error connecting: %v", err)
567+
}
568+
addr := nc.LocalAddr()
569+
if addr == "" {
570+
t.Fatalf("Expected non-empty local address")
571+
}
572+
// Verify it's a valid address format
573+
host, port, err := net.SplitHostPort(addr)
574+
if err != nil {
575+
t.Fatalf("Expected valid host:port format, got %q: %v", addr, err)
576+
}
577+
if host == "" {
578+
t.Fatalf("Expected non-empty host in address %q", addr)
579+
}
580+
if port == "" {
581+
t.Fatalf("Expected non-empty port in address %q", addr)
582+
}
583+
nc.Close()
584+
if addr := nc.LocalAddr(); addr != "" {
585+
t.Fatalf("Expected empty result for closed connection, got %q", addr)
586+
}
587+
}
588+
556589
func TestSubscribeSyncRace(t *testing.T) {
557590
s := RunServerOnPort(TEST_PORT)
558591
defer s.Shutdown()

0 commit comments

Comments
 (0)