-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathportstat.go
78 lines (61 loc) · 1.45 KB
/
portstat.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
package nux
import (
"bufio"
"bytes"
"fmt"
"io"
"strconv"
"strings"
"github.com/toolkits/file"
"github.com/toolkits/slice"
"github.com/toolkits/sys"
)
// ListeningPorts 为了兼容老代码
func ListeningPorts() ([]int64, error) {
return TcpPorts()
}
func TcpPorts() ([]int64, error) {
return listeningPorts("sh", "-c", "ss -t -l -n")
}
func UdpPorts() ([]int64, error) {
return listeningPorts("sh", "-c", "ss -u -a -n")
}
func listeningPorts(name string, args ...string) ([]int64, error) {
ports := []int64{}
bs, err := sys.CmdOutBytes(name, args...)
if err != nil {
return ports, err
}
reader := bufio.NewReader(bytes.NewBuffer(bs))
// ignore the first line
line, err := file.ReadLine(reader)
if err != nil {
return ports, err
}
for {
line, err = file.ReadLine(reader)
if err == io.EOF {
err = nil
break
} else if err != nil {
return ports, err
}
fields := strings.Fields(string(line))
fieldsLen := len(fields)
if fieldsLen != 4 && fieldsLen != 5 {
return ports, fmt.Errorf("output of %s format not supported", name)
}
portColumnIndex := 2
if fieldsLen == 5 {
portColumnIndex = 3
}
location := strings.LastIndex(fields[portColumnIndex], ":")
port := fields[portColumnIndex][location+1:]
if p, e := strconv.ParseInt(port, 10, 64); e != nil {
return ports, fmt.Errorf("parse port to int64 fail: %s", e.Error())
} else {
ports = append(ports, p)
}
}
return slice.UniqueInt64(ports), nil
}