forked from toolkits/nux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathportstat.go
72 lines (57 loc) · 1.35 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
package nux
import (
"bufio"
"bytes"
"fmt"
"github.com/toolkits/file"
"github.com/toolkits/slice"
"github.com/toolkits/sys"
"io"
"strconv"
"strings"
)
func ListeningPorts() ([]int64, error) {
return listeningPorts("ss", "-t", "-l", "-n")
}
func UdpPorts() ([]int64, error) {
return listeningPorts("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
}