@@ -8,9 +8,11 @@ import (
8
8
"regexp"
9
9
"strconv"
10
10
"strings"
11
+ "time"
11
12
)
12
13
13
14
type Entry struct {
15
+ TCP bool
14
16
IP net.IP
15
17
Port int
16
18
}
@@ -27,7 +29,7 @@ type Entry struct {
27
29
// ipv4 IP address. We need to detect this IP.
28
30
// --dport is the destination port. We need to detect this port
29
31
// -j DNAT this tells us it's the line doing the port forwarding.
30
- var findPortRegex = regexp .MustCompile (`-A\s+CNI-DN-\w*\s+(?:-d ((?:\b25[0-5]|\b2[0-4][0-9]|\b[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}))?(?:/32\s+)?-p .*--dport (\d+) -j DNAT` )
32
+ var findPortRegex = regexp .MustCompile (`-A\s+CNI-DN-\w*\s+(?:-d ((?:\b25[0-5]|\b2[0-4][0-9]|\b[01]?[0-9][0-9]?)(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}))?(?:/32\s+)?-p (tcp)? .*--dport (\d+) -j DNAT` )
31
33
32
34
func GetPorts () ([]Entry , error ) {
33
35
// TODO: add support for ipv6
@@ -50,19 +52,29 @@ func GetPorts() ([]Entry, error) {
50
52
return nil , err
51
53
}
52
54
53
- return parsePortsFromRules (res )
55
+ pts , err := parsePortsFromRules (res )
56
+ if err != nil {
57
+ return nil , err
58
+ }
59
+
60
+ return checkPortsOpen (pts )
54
61
}
55
62
56
63
func parsePortsFromRules (rules []string ) ([]Entry , error ) {
57
64
var entries []Entry
58
65
for _ , rule := range rules {
59
66
if found := findPortRegex .FindStringSubmatch (rule ); found != nil {
60
- if len (found ) == 3 {
61
- port , err := strconv .Atoi (found [2 ])
67
+ if len (found ) == 4 {
68
+ port , err := strconv .Atoi (found [3 ])
62
69
if err != nil {
63
70
return nil , err
64
71
}
65
72
73
+ istcp := false
74
+ if found [2 ] == "tcp" {
75
+ istcp = true
76
+ }
77
+
66
78
// if the IP is blank the port forwarding the portforwarding,
67
79
// which gets information from this, will skip it. When no IP
68
80
// is present localhost will work.
@@ -73,6 +85,7 @@ func parsePortsFromRules(rules []string) ([]Entry, error) {
73
85
ent := Entry {
74
86
IP : net .ParseIP (ip ),
75
87
Port : port ,
88
+ TCP : istcp ,
76
89
}
77
90
entries = append (entries , ent )
78
91
}
@@ -109,3 +122,20 @@ func listNATRules(pth string) ([]string, error) {
109
122
110
123
return rules , nil
111
124
}
125
+
126
+ func checkPortsOpen (pts []Entry ) ([]Entry , error ) {
127
+ var entries []Entry
128
+ for _ , pt := range pts {
129
+ if pt .TCP {
130
+ conn , err := net .DialTimeout ("tcp" , net .JoinHostPort (pt .IP .String (), strconv .Itoa (pt .Port )), time .Second )
131
+ if err == nil && conn != nil {
132
+ conn .Close ()
133
+ entries = append (entries , pt )
134
+ }
135
+ } else {
136
+ entries = append (entries , pt )
137
+ }
138
+ }
139
+
140
+ return entries , nil
141
+ }
0 commit comments