-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
ports.go
70 lines (58 loc) · 1.11 KB
/
ports.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
package portforward
import (
"errors"
"strconv"
"strings"
)
type forwardedPort struct {
local int
remote int
protocol string
}
func parsePorts(args []string) ([]forwardedPort, error) {
ports := make([]forwardedPort, len(args))
for i, arg := range args {
forwardedPort, err := parsePort(arg)
if err != nil {
return ports, err
}
ports[i] = forwardedPort
}
return ports, nil
}
const (
protocolTCP = "tcp"
protocolUDP = "udp"
)
func parsePort(arg string) (forwardedPort, error) {
var (
port = forwardedPort{
// default to tcp
protocol: protocolTCP,
}
err error
)
protocol := strings.Split(arg, "/")
if len(protocol) > 1 {
port.protocol = protocol[0]
arg = protocol[1]
}
ports := strings.FieldsFunc(arg, func(r rune) bool {
return r == ':'
})
if len(ports) < 1 {
return port, errors.New("invalid port, missing local and/or remote port")
}
port.local, err = strconv.Atoi(ports[0])
if err != nil {
return port, err
}
port.remote = port.local
if len(ports) > 1 {
port.remote, err = strconv.Atoi(ports[1])
if err != nil {
return port, err
}
}
return port, nil
}