Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions natpmp.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ func (n *natpmpNAT) AddPortMapping(protocol string, internalPort int, descriptio

timeoutInSeconds := int(timeout / time.Second)

// Try to remap the same port.
if externalPort := n.ports[internalPort]; externalPort > 0 {
_, err = n.c.AddPortMapping(protocol, internalPort, externalPort, timeoutInSeconds)
if err == nil {
Expand All @@ -93,6 +94,14 @@ func (n *natpmpNAT) AddPortMapping(protocol string, internalPort int, descriptio
}
}

// Try to map our internal port.
_, err = n.c.AddPortMapping(protocol, internalPort, internalPort, timeoutInSeconds)
if err == nil {
n.ports[internalPort] = internalPort
return internalPort, nil
}

// Try three random ports.
for i := 0; i < 3; i++ {
externalPort := randomPort()
_, err = n.c.AddPortMapping(protocol, internalPort, externalPort, timeoutInSeconds)
Expand Down
9 changes: 9 additions & 0 deletions upnp.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,13 +229,22 @@ func (u *upnp_NAT) AddPortMapping(protocol string, internalPort int, description

timeoutInSeconds := uint32(timeout / time.Second)

// Try to remap the same port.
if externalPort := u.ports[internalPort]; externalPort > 0 {
err = u.c.AddPortMapping("", uint16(externalPort), mapProtocol(protocol), uint16(internalPort), ip.String(), true, description, timeoutInSeconds)
if err == nil {
return externalPort, nil
}
}

// Try to map our internal port.
err = u.c.AddPortMapping("", uint16(internalPort), mapProtocol(protocol), uint16(internalPort), ip.String(), true, description, timeoutInSeconds)
if err == nil {
u.ports[internalPort] = internalPort
return internalPort, nil
}

// Try three random ports.
for i := 0; i < 3; i++ {
externalPort := randomPort()
err = u.c.AddPortMapping("", uint16(externalPort), mapProtocol(protocol), uint16(internalPort), ip.String(), true, description, timeoutInSeconds)
Expand Down