-
Notifications
You must be signed in to change notification settings - Fork 17
/
ports.go
79 lines (65 loc) · 1.82 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
71
72
73
74
75
76
77
78
79
package cagent
import (
"fmt"
"syscall"
"github.com/shirou/gopsutil/net"
log "github.com/sirupsen/logrus"
"github.com/cloudradar-monitoring/cagent/pkg/common"
"github.com/cloudradar-monitoring/cagent/pkg/monitoring/processes"
)
type PortStat struct {
Protocol string `json:"proto"`
LocalAddress string `json:"addr"`
PID int32 `json:"pid,omitempty"`
ProgramName string `json:"program,omitempty"`
}
// PortsResult lists all active connections
func (ca *Cagent) PortsResult(processList []*processes.ProcStat) (common.MeasurementsMap, error) {
connections, err := net.Connections("inet")
if err != nil {
log.Error("[PORTS] could not list connections: ", err.Error())
return nil, err
}
var ports []PortStat
for _, conn := range connections {
state := conn.Status
// some connection types do not have 'state'. They are active by default.
isActiveConnection := state == "LISTEN" || state == "NONE" || state == ""
if !isActiveConnection {
continue
}
var programName string
if conn.Pid != 0 {
for _, proc := range processList {
if int32(proc.PID) == conn.Pid {
programName = proc.Name
break
}
}
}
ports = append(ports, PortStat{
Protocol: formatConnectionProtocol(conn.Family, conn.Type),
LocalAddress: formatNetAddr(&conn.Laddr),
PID: conn.Pid,
ProgramName: programName,
})
}
log.Debugf("[PORTS] results: %d", len(ports))
return common.MeasurementsMap{"list": ports}, nil
}
func formatNetAddr(addr *net.Addr) string {
return fmt.Sprintf("%s:%d", addr.IP, addr.Port)
}
func formatConnectionProtocol(family, socketType uint32) string {
var version string
if family == syscall.AF_INET6 {
version = "6"
}
var baseProto string
if socketType == syscall.SOCK_STREAM {
baseProto = "tcp"
} else {
baseProto = "udp"
}
return baseProto + version
}