-
Notifications
You must be signed in to change notification settings - Fork 5
/
openup.go
63 lines (61 loc) · 1.6 KB
/
openup.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
package main
import (
"flag"
"fmt"
"github.com/jcuga/go-upnp"
"os"
)
func main() {
displayExternalIpPtr := flag.Bool("ip", false, "Display external IP address and exit.")
useUdpPtr := flag.Bool("udp", false, "Use UDP (instead of TCP) when opening/closing port forward.")
doClosePtr := flag.Bool("close", false, "Close (as opposed to open) the given port.")
portPtr := flag.Int("port", -1, "Port to open/close")
flag.Parse()
if *displayExternalIpPtr {
// connect to router
d, dErr := upnp.Discover()
if dErr != nil {
fmt.Printf("Error discovering router: %v\n", dErr)
os.Exit(1)
}
// discover external IP
ip, ipErr := d.ExternalIP()
if ipErr != nil {
fmt.Printf("Error fetching external IP address: %v\n", ipErr)
os.Exit(1)
}
fmt.Println("Your external IP is:", ip)
return
}
if *portPtr <= 0 {
fmt.Printf("Invalid port number, must be > 0. Got: %d\n", *portPtr)
os.Exit(1)
}
d, dErr := upnp.Discover()
if dErr != nil {
fmt.Printf("Error discovering router: %v\n", dErr)
os.Exit(1)
}
var proto string
if *useUdpPtr {
proto = "UDP"
} else {
proto = "TCP"
}
// Open/Close the given port/protocol
if *doClosePtr {
fmt.Printf("Closing port forward for %s port %d\n", proto, *portPtr)
cErr := d.Clear(uint16(*portPtr), proto)
if cErr != nil {
fmt.Printf("Error closing port forward: %v\n", cErr)
os.Exit(1)
}
} else {
fmt.Printf("Opening port forward for %s port %d\n", proto, *portPtr)
fErr := d.Forward(uint16(*portPtr), "Requested by openup util.", proto)
if fErr != nil {
fmt.Printf("Error closing port forward: %v\n", fErr)
os.Exit(1)
}
}
}