-
Notifications
You must be signed in to change notification settings - Fork 0
/
natpmp.go
119 lines (95 loc) · 2.29 KB
/
natpmp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package nat
import (
"net"
"time"
"github.com/jackpal/gateway"
natpmp "github.com/jackpal/go-nat-pmp"
)
var (
_ NAT = (*natpmpNAT)(nil)
)
func discoverNATPMP() <-chan NAT {
res := make(chan NAT, 1)
ip, err := gateway.DiscoverGateway()
if err == nil {
go discoverNATPMPWithAddr(res, ip)
}
return res
}
func discoverNATPMPWithAddr(c chan NAT, ip net.IP) {
client := natpmp.NewClient(ip)
_, err := client.GetExternalAddress()
if err != nil {
return
}
c <- &natpmpNAT{client, ip, make(map[int]int)}
}
type natpmpNAT struct {
c *natpmp.Client
gateway net.IP
ports map[int]int
}
func (n *natpmpNAT) GetDeviceAddress() (addr net.IP, err error) {
return n.gateway, nil
}
func (n *natpmpNAT) GetInternalAddress() (addr net.IP, err error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, iface := range ifaces {
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
switch x := addr.(type) {
case *net.IPNet:
if x.Contains(n.gateway) {
return x.IP, nil
}
}
}
}
return nil, ErrNoInternalAddress
}
func (n *natpmpNAT) GetExternalAddress() (addr net.IP, err error) {
res, err := n.c.GetExternalAddress()
if err != nil {
return nil, err
}
d := res.ExternalIPAddress
return net.IPv4(d[0], d[1], d[2], d[3]), nil
}
func (n *natpmpNAT) AddPortMapping(protocol string, internalPort int, description string, timeout time.Duration) (int, error) {
var (
err error
)
timeoutInSeconds := int(timeout / time.Second)
if externalPort := n.ports[internalPort]; externalPort > 0 {
_, err = n.c.AddPortMapping(protocol, internalPort, externalPort, timeoutInSeconds)
if err == nil {
n.ports[internalPort] = externalPort
return externalPort, nil
}
}
for i := 0; i < 3; i++ {
externalPort := randomPort()
_, err = n.c.AddPortMapping(protocol, internalPort, externalPort, timeoutInSeconds)
if err == nil {
n.ports[internalPort] = externalPort
return externalPort, nil
}
}
return 0, err
}
func (n *natpmpNAT) DeletePortMapping(protocol string, internalPort int) (err error) {
delete(n.ports, internalPort)
return nil
}
func (u *natpmpNAT) DeleteExternalPortMapping(protocol string, externalPort int) error {
return nil
}
func (n *natpmpNAT) Type() string {
return "NAT-PMP"
}