-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflowtrack.go
106 lines (86 loc) · 2.36 KB
/
flowtrack.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
package flowtrack
import (
"fmt"
"net"
)
var (
topFlowsPackets = map[flowkey]uint64{}
topFlowsBytes = map[flowkey]uint64{}
topSourcePackets = map[addrPortKey]uint64{}
topSourceBytes = map[addrPortKey]uint64{}
topDestPackets = map[addrPortKey]uint64{}
topDestBytes = map[addrPortKey]uint64{}
)
func Process(source, destination net.IP, sourcePort, destPort, bytes int) {
flowKey := generateFlowKey(source, destination, sourcePort, destPort)
sourceKey := generateAddrPortKey(source, sourcePort)
destKey := generateAddrPortKey(destination, destPort)
topFlowsPackets[flowKey] += 1
topFlowsBytes[flowKey] += uint64(bytes)
topSourcePackets[sourceKey] += 1
topSourceBytes[sourceKey] += uint64(bytes)
topDestPackets[destKey] += 1
topDestBytes[destKey] += uint64(bytes)
}
func PrintTopN(n int) {
fmt.Printf(" --- Top %d Flows ---\n", n)
keys := sortFlowKeyMap(topFlowsPackets)
for i, key := range keys {
if i >= n {
break
}
fmt.Printf("%s [%d packets]\n", key, topFlowsPackets[key])
}
fmt.Println()
keys = sortFlowKeyMap(topFlowsBytes)
for i, key := range keys {
if i >= n {
break
}
fmt.Printf("%s [%d bytes]\n", key, topFlowsBytes[key])
}
fmt.Println()
fmt.Printf(" --- Top %d Sources ---\n", n)
addrKeys := sortAddrPortKeySortableMap(topSourcePackets)
for i, key := range addrKeys {
if i >= n {
break
}
fmt.Printf("%s [%d packets]\n", key, topSourcePackets[key])
}
fmt.Println()
addrKeys = sortAddrPortKeySortableMap(topSourceBytes)
for i, key := range addrKeys {
if i >= n {
break
}
fmt.Printf("%s [%d bytes]\n", key, topSourceBytes[key])
}
fmt.Println()
fmt.Printf(" --- Top %d Destinations ---\n", n)
addrKeys = sortAddrPortKeySortableMap(topDestPackets)
for i, key := range addrKeys {
if i >= n {
break
}
fmt.Printf("%s [%d packets]\n", key, topDestPackets[key])
}
fmt.Println()
addrKeys = sortAddrPortKeySortableMap(topDestBytes)
for i, key := range addrKeys {
if i >= n {
break
}
fmt.Printf("%s [%d bytes]\n", key, topDestBytes[key])
}
fmt.Println("\nTotal flows seen this window:", len(topFlowsBytes))
fmt.Println(" ---")
}
func Reset() {
topFlowsPackets = map[flowkey]uint64{}
topFlowsBytes = map[flowkey]uint64{}
topSourcePackets = map[addrPortKey]uint64{}
topSourceBytes = map[addrPortKey]uint64{}
topDestPackets = map[addrPortKey]uint64{}
topDestBytes = map[addrPortKey]uint64{}
}