66 "fmt"
77 "net/netip"
88 "sync"
9+ "sync/atomic"
910 "time"
1011
1112 logging "github.com/ipfs/go-log/v2"
@@ -56,11 +57,11 @@ func DiscoverNAT(ctx context.Context) (*NAT, error) {
5657 ctx , cancel := context .WithCancel (context .Background ())
5758 nat := & NAT {
5859 nat : natInstance ,
59- extAddr : extAddr ,
6060 mappings : make (map [entry ]int ),
6161 ctx : ctx ,
6262 ctxCancel : cancel ,
6363 }
64+ nat .extAddr .Store (& extAddr )
6465 nat .refCount .Add (1 )
6566 go func () {
6667 defer nat .refCount .Done ()
@@ -77,7 +78,7 @@ type NAT struct {
7778 natmu sync.Mutex
7879 nat nat.NAT
7980 // External IP of the NAT. Will be renewed periodically (every CacheTime).
80- extAddr netip.Addr
81+ extAddr atomic. Pointer [ netip.Addr ]
8182
8283 refCount sync.WaitGroup
8384 ctx context.Context
@@ -103,15 +104,15 @@ func (nat *NAT) GetMapping(protocol string, port int) (addr netip.AddrPort, foun
103104 nat .mappingmu .Lock ()
104105 defer nat .mappingmu .Unlock ()
105106
106- if ! nat .extAddr .IsValid () {
107+ if ! nat .extAddr .Load (). IsValid () {
107108 return netip.AddrPort {}, false
108109 }
109110 extPort , found := nat .mappings [entry {protocol : protocol , port : port }]
110111 // The mapping may have an invalid port.
111112 if ! found || extPort == 0 {
112113 return netip.AddrPort {}, false
113114 }
114- return netip .AddrPortFrom (nat .extAddr , uint16 (extPort )), true
115+ return netip .AddrPortFrom (* nat .extAddr . Load () , uint16 (extPort )), true
115116}
116117
117118// AddMapping attempts to construct a mapping on protocol and internal port.
@@ -206,7 +207,7 @@ func (nat *NAT) background() {
206207 if err == nil {
207208 extAddr , _ = netip .AddrFromSlice (extIP )
208209 }
209- nat .extAddr = extAddr
210+ nat .extAddr . Store ( & extAddr )
210211 nextAddrUpdate = time .Now ().Add (CacheTime )
211212 }
212213 t .Reset (time .Until (minTime (nextAddrUpdate , nextMappingUpdate )))
0 commit comments