diff --git a/p2p/host/basic/basic_host.go b/p2p/host/basic/basic_host.go index 431137911e..37cfa10995 100644 --- a/p2p/host/basic/basic_host.go +++ b/p2p/host/basic/basic_host.go @@ -843,11 +843,10 @@ func (h *BasicHost) AllAddrs() []ma.Multiaddr { finalAddrs = network.DedupAddrs(finalAddrs) - // natmgr is nil if we do not use nat option; - if h.natmgr != nil { + // use nat mappings if we have them + if h.natmgr != nil && h.natmgr.HasDiscoveredNAT() { // We have successfully mapped ports on our NAT. Use those // instead of observed addresses (mostly). - // Next, apply this mapping to our addresses. for _, listen := range listenAddrs { extMaddr := h.natmgr.GetMapping(listen) diff --git a/p2p/host/basic/natmgr.go b/p2p/host/basic/natmgr.go index 120e2b826d..8e8fbea347 100644 --- a/p2p/host/basic/natmgr.go +++ b/p2p/host/basic/natmgr.go @@ -21,6 +21,7 @@ import ( // and tries to obtain port mappings for those. type NATManager interface { GetMapping(ma.Multiaddr) ma.Multiaddr + HasDiscoveredNAT() bool io.Closer } @@ -86,6 +87,12 @@ func (nmgr *natManager) Close() error { return nil } +func (nmgr *natManager) HasDiscoveredNAT() bool { + nmgr.natMx.RLock() + defer nmgr.natMx.RUnlock() + return nmgr.nat != nil +} + func (nmgr *natManager) background(ctx context.Context) { defer nmgr.refCount.Done()