diff --git a/natpmp.go b/natpmp.go index 395a5dd..749a007 100644 --- a/natpmp.go +++ b/natpmp.go @@ -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 { @@ -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) diff --git a/upnp.go b/upnp.go index caad350..4eea023 100644 --- a/upnp.go +++ b/upnp.go @@ -229,6 +229,7 @@ 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 { @@ -236,6 +237,14 @@ func (u *upnp_NAT) AddPortMapping(protocol string, internalPort int, description } } + // 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)