File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -2292,6 +2292,21 @@ func (nc *Conn) ConnectedAddr() string {
2292
2292
return nc .conn .RemoteAddr ().String ()
2293
2293
}
2294
2294
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
+
2295
2310
// ConnectedServerId reports the connected server's Id
2296
2311
func (nc * Conn ) ConnectedServerId () string {
2297
2312
if nc == nil {
Original file line number Diff line number Diff line change @@ -553,6 +553,39 @@ func TestConnectedAddr(t *testing.T) {
553
553
}
554
554
}
555
555
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
+
556
589
func TestSubscribeSyncRace (t * testing.T ) {
557
590
s := RunServerOnPort (TEST_PORT )
558
591
defer s .Shutdown ()
You can’t perform that action at this time.
0 commit comments