-
Notifications
You must be signed in to change notification settings - Fork 33
/
main.go
91 lines (71 loc) · 2.34 KB
/
main.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
// This example shows how to set up NAT traversal. The example uses go-nat
// package, which only works for routers that support UPnP and NAT-PMP protocol.
// NAT traversal can also be set up in middleware such as NetworkWillStart and
// LocalNodeWillStart.
// You may need to get go-nat package by `go get github.com/nknorg/go-nat` in
// order to run this example.
// Run with default options: go run main.go
// Show usage: go run main.go -h
package main
import (
"flag"
"os"
"os/signal"
"time"
gonat "github.com/nknorg/go-nat"
"github.com/nknorg/nnet"
"github.com/nknorg/nnet/log"
"github.com/nknorg/nnet/transport"
)
func main() {
transportPtr := flag.String("t", "tcp", "transport type, tcp or kcp")
externalPortPtr := flag.Uint("e", 10086, "external port to map from")
internalPortPtr := flag.Uint("i", 12580, "internal port to map to")
flag.Parse()
conf := &nnet.Config{
Port: uint16(*externalPortPtr),
Transport: *transportPtr,
}
nn, err := nnet.NewNNet(nil, conf)
if err != nil {
log.Error(err)
return
}
transport, err := transport.NewTransport(*transportPtr, nn.GetConfig().SupportedTransports)
if err != nil {
log.Error(err)
return
}
transportProtocol := transport.GetNetwork()
// Begin of NAT setup
// This can also be done in middleware like NetworkWillStart or LocalNodeWillStart
// ==========================================================================
log.Info("Discovering NAT gateway...")
nat, err := gonat.DiscoverGateway()
if err != nil {
log.Error(err)
return
}
log.Infof("Found %s gateway", nat.Type())
externalPort, internalPort, err := nat.AddPortMapping(transportProtocol, int(*externalPortPtr), int(*internalPortPtr), "nnet", 10*time.Second)
if err != nil {
log.Error(err)
return
}
defer nat.DeletePortMapping(transportProtocol, int(*externalPortPtr))
log.Infof("Mapped external port %d to internal port %d", externalPort, internalPort)
// SetInternalPort should only be called before node starts
nn.GetLocalNode().SetInternalPort(uint16(internalPort))
// ==========================================================================
// End of NAT setup
err = nn.Start(true)
if err != nil {
log.Error(err)
return
}
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt)
<-signalChan
log.Info("\nReceived an interrupt, stopping...\n")
nn.Stop(nil)
}