This repository has been archived by the owner on Jul 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
upnp.go
executable file
·64 lines (54 loc) · 1.71 KB
/
upnp.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
// Package nattraversal provides tools for acquiring ports on a Network Address Translator (NAT).
package nattraversal
import (
"fmt"
"os"
"os/user"
"github.com/libonomy/libonomy-p2p/nattraversal/upnp"
)
// GetExternalIP returns a string formatted external IP address from a UPnP-enabled NAT on the network, if such device
// is discovered.
func GetExternalIP() (string, error) {
// connect to router
d, err := upnp.Discover()
if err != nil {
return "", fmt.Errorf("failed to connect to router: %v", err)
}
// discover external IP
ip, err := d.ExternalIP()
if err != nil {
return "", fmt.Errorf("failed to discover external IP: %v", err)
}
return ip, nil
}
func getPortDesc() string {
hostname, err := os.Hostname()
if err != nil {
hostname = "unknown"
}
username := "unknown"
current, err := user.Current()
if err == nil {
username = current.Username
}
portDesc := fmt.Sprintf("libonomy:%s@%s", username, hostname)
return portDesc
}
// UPNPGateway is the interface of a UPnP gateway. It supports forwarding a port and clearing a forwarding rule.
type UPNPGateway interface {
Forward(port uint16, desc string) error
Clear(port uint16) error
}
// DiscoverUPNPGateway returns a UPNPGateway if one is found on the network. This process is long - about 30 seconds and
// is expected to fail in some network setups.
func DiscoverUPNPGateway() (UPNPGateway, error) {
return upnp.Discover()
}
// AcquirePortFromGateway sets up UDP and TCP forwarding rules for the given port on the given gateway.
func AcquirePortFromGateway(gateway UPNPGateway, port uint16) error {
err := gateway.Forward(port, getPortDesc())
if err != nil {
return fmt.Errorf("failed to forward port %d: %v", port, err)
}
return nil
}