-
Notifications
You must be signed in to change notification settings - Fork 63
/
conn_darwin.go
100 lines (81 loc) · 1.97 KB
/
conn_darwin.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//go:build freebsd || darwin
// +build freebsd darwin
package main
import (
"bytes"
"context"
"os/exec"
"strconv"
"strings"
"time"
)
type lsofConn struct {
invoker Invoker
}
type Invoker interface {
Exec() ([]byte, error)
}
type lsofInvoker struct{}
// Exec executes the command and return the output bytes of it.
func (i lsofInvoker) Exec() ([]byte, error) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, "lsof", "-n", "-R", "-P", "-iTCP", "-iUDP", "-s", "TCP:ESTABLISHED", "+c", "0")
var buf bytes.Buffer
cmd.Stdout = &buf
cmd.Stderr = &buf
if err := cmd.Start(); err != nil {
return buf.Bytes(), err
}
if err := cmd.Wait(); err != nil {
return buf.Bytes(), err
}
return buf.Bytes(), nil
}
func (lc *lsofConn) GetOpenSockets() (OpenSockets, error) {
sockets := make(OpenSockets)
output, err := lc.invoker.Exec()
if err != nil {
return sockets, err
}
lines := strings.Split(string(output), "\n")
for _, line := range lines {
fields := strings.Fields(line)
if len(fields) < 10 {
continue
}
procName := strings.ReplaceAll(fields[0], "\\x20", " ")
pid, _ := strconv.Atoi(fields[1])
procInfo := ProcessInfo{Pid: pid, Name: procName}
switch fields[8] {
case "TCP":
addr := strings.Split(fields[9], "->")
if len(addr) != 2 {
continue
}
ipport := strings.Split(addr[0], ":")
if len(ipport) != 2 {
continue
}
port, err := strconv.Atoi(ipport[1])
if err != nil {
continue
}
sockets[LocalSocket{IP: ipport[0], Port: uint16(port), Protocol: ProtoTCP}] = procInfo
case "UDP":
ipport := strings.Split(fields[9], ":")
if len(ipport) != 2 {
continue
}
port, err := strconv.Atoi(ipport[1])
if err != nil {
continue
}
sockets[LocalSocket{IP: ipport[0], Port: uint16(port), Protocol: ProtoUDP}] = procInfo
}
}
return sockets, nil
}
func GetSocketFetcher() SocketFetcher {
return &lsofConn{invoker: lsofInvoker{}}
}