Skip to content

Commit

Permalink
good
Browse files Browse the repository at this point in the history
  • Loading branch information
qqqeck committed Jul 17, 2024
1 parent 788ec72 commit 416abd0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
5 changes: 3 additions & 2 deletions p2p/nat/nat.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,7 @@ func (n *autodisc) DeleteMapping(protocol string, extport, intport int) error {

func (n *autodisc) ExternalIP() (net.IP, error) {
if err := n.wait(); err != nil {
n.found = nil
return nil, err
}
return n.found.ExternalIP()
Expand All @@ -228,11 +229,11 @@ func (n *autodisc) String() string {

// wait blocks until auto-discovery has been performed.
func (n *autodisc) wait() error {
n.once.Do(func() {
if n.found == nil {
n.mu.Lock()
n.found = n.doit()
n.mu.Unlock()
})
}
if n.found == nil {
return fmt.Errorf("no %s router discovered", n.what)
}
Expand Down
14 changes: 8 additions & 6 deletions p2p/nat/natupnp.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,6 @@ func (n *upnp) AddMapping(protocol string, extport, intport int, desc string, li
}
protocol = strings.ToUpper(protocol)
lifetimeS := uint32(lifetime / time.Second)
n.DeleteMapping(protocol, extport, intport)

err = n.withRateLimit(func() error {
return n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
Expand All @@ -110,12 +109,15 @@ func (n *upnp) addAnyPortMapping(protocol string, extport, intport int, ip net.I
}
// It will retry with a random port number if the client does
// not support AddAnyPortMapping.
extport = n.randomPort()
err := n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
if err != nil {
return 0, err
var err error
for i := 0; i < 3; i++ {
extport = n.randomPort()
err = n.client.AddPortMapping("", uint16(extport), protocol, uint16(intport), ip.String(), true, desc, lifetimeS)
if err == nil {
return uint16(extport), nil
}
}
return uint16(extport), nil
return 0, err
}

func (n *upnp) randomPort() int {
Expand Down

0 comments on commit 416abd0

Please sign in to comment.