-
Notifications
You must be signed in to change notification settings - Fork 63
/
pcap.go
139 lines (111 loc) · 2.31 KB
/
pcap.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package main
import (
"fmt"
"strings"
"sync"
"github.com/google/gopacket/pcap"
)
type RemoteSocket struct {
IP string
Port uint16
}
type LocalSocket struct {
IP string
Port uint16
Protocol Protocol
}
type Connection struct {
Local LocalSocket
Remote RemoteSocket
}
type ProcessInfo struct {
Pid int
Name string
}
func (p ProcessInfo) String() string {
return fmt.Sprintf("<%d>:%s", p.Pid, p.Name)
}
type (
OpenSockets map[LocalSocket]ProcessInfo
Utilization map[Connection]*ConnectionInfo
)
type SocketFetcher interface {
GetOpenSockets() (OpenSockets, error)
}
type Protocol string
const (
ProtoTCP Protocol = "tcp"
ProtoUDP Protocol = "udp"
)
type Direction uint8
const (
DirectionUpload Direction = iota
DirectionDownload
)
type ConnectionInfo struct {
Interface string
UploadPackets int
DownloadPackets int
UploadBytes int
DownloadBytes int
}
type Segment struct {
Interface string
DataLen int
Connection Connection
Direction Direction
}
type Sinker struct {
mut sync.Mutex
utilization Utilization
}
func NewSinker() *Sinker {
return &Sinker{utilization: make(Utilization)}
}
func (c *Sinker) Fetch(seg Segment) {
c.mut.Lock()
defer c.mut.Unlock()
if _, ok := c.utilization[seg.Connection]; !ok {
c.utilization[seg.Connection] = &ConnectionInfo{
Interface: seg.Interface,
}
}
switch seg.Direction {
case DirectionUpload:
c.utilization[seg.Connection].UploadBytes += seg.DataLen
c.utilization[seg.Connection].UploadPackets += 1
case DirectionDownload:
c.utilization[seg.Connection].DownloadBytes += seg.DataLen
c.utilization[seg.Connection].DownloadPackets += 1
}
}
func (c *Sinker) GetUtilization() Utilization {
c.mut.Lock()
defer c.mut.Unlock()
utilization := c.utilization
c.utilization = make(Utilization)
return utilization
}
func ListAllDevices() ([]pcap.Interface, error) {
return pcap.FindAllDevs()
}
func listPrefixDevices(prefix []string, allowAll bool) ([]pcap.Interface, error) {
all, err := ListAllDevices()
if err != nil {
return nil, err
}
var devs []pcap.Interface
for _, device := range all {
if allowAll {
devs = append(devs, device)
continue
}
for _, pre := range prefix {
if strings.HasPrefix(device.Name, pre) {
devs = append(devs, device)
break
}
}
}
return devs, nil
}