From 9970d8e668b0eeaa3ad64532b98c9a51a050e3b2 Mon Sep 17 00:00:00 2001 From: wlynxg Date: Thu, 21 Nov 2024 17:51:47 +0800 Subject: [PATCH] fix: don't use invalid port 0 when NATMap fails --- p2p/host/basic/basic_host.go | 9 ++++++++- p2p/net/nat/nat.go | 2 +- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/p2p/host/basic/basic_host.go b/p2p/host/basic/basic_host.go index 820411bd27..b88ff3f13a 100644 --- a/p2p/host/basic/basic_host.go +++ b/p2p/host/basic/basic_host.go @@ -893,6 +893,8 @@ func (h *BasicHost) AllAddrs() []ma.Multiaddr { finalAddrs = ma.Unique(finalAddrs) + // counts the number of addresses that are correctly port mapped + successMapCnt := 0 // use nat mappings if we have them if h.natmgr != nil && h.natmgr.HasDiscoveredNAT() { // We have successfully mapped ports on our NAT. Use those @@ -929,6 +931,8 @@ func (h *BasicHost) AllAddrs() []ma.Multiaddr { continue } + successMapCnt++ + for _, addr := range resolved { // Now, check if we have any observed addresses that // differ from the one reported by the router. Routers @@ -953,7 +957,10 @@ func (h *BasicHost) AllAddrs() []ma.Multiaddr { } } } - } else { + } + + // if there is no properly handled port mapping address, add the observed address directly + if successMapCnt > 0 { var observedAddrs []ma.Multiaddr if h.ids != nil { observedAddrs = h.ids.OwnObservedAddrs() diff --git a/p2p/net/nat/nat.go b/p2p/net/nat/nat.go index 28ffd4a5b2..23805fcc10 100644 --- a/p2p/net/nat/nat.go +++ b/p2p/net/nat/nat.go @@ -107,7 +107,7 @@ func (nat *NAT) GetMapping(protocol string, port int) (addr netip.AddrPort, foun return netip.AddrPort{}, false } extPort, found := nat.mappings[entry{protocol: protocol, port: port}] - if !found { + if !found || extPort == 0 { return netip.AddrPort{}, false } return netip.AddrPortFrom(nat.extAddr, uint16(extPort)), true