-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
104 lines (84 loc) · 2.44 KB
/
main.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
package main
import "fmt"
import "github.com/google/gopacket/pcap"
import "github.com/google/gopacket"
import "github.com/google/gopacket/layers"
import "flag"
import "encoding/json"
var path = flag.String("pcap-file", "", "Path to a PCAP file.")
var live = flag.Bool("live", false, "Live capture? If set to true capture packets from specified iface.")
var snaplen = flag.Int("snaplen", 8192, "Snaplen: Max length of captured payload per packet.")
var iface = flag.String("iface", "eth0", "Interface to use.")
var plusOnly = flag.Bool("plus-only", true, "Only plus? If set to true ignore non-PLUS packets.")
var dumpType = flag.String("dump-type", "gopacket", "Dump packets as JSON? Available: gopacket, json")
var prettyJson = flag.Bool("pretty-json", false, "Pretty print JSON?")
func main() {
flag.Parse()
if *path == "" && *live == false {
flag.Usage()
return
}
layers.EnableHeuristics()
if !*live {
if handle, err := pcap.OpenOffline(*path); err != nil {
panic(err)
} else {
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
runWithPacketSource(packetSource)
}
} else {
if handle, err := pcap.OpenLive(*iface, int32(*snaplen), true, pcap.BlockForever); err != nil {
panic(err)
} else {
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
runWithPacketSource(packetSource)
}
}
}
type dumpLayer struct {
LayerName string
Layer gopacket.Layer
}
func dumpPacket(packet gopacket.Packet) {
switch *dumpType {
case "json":
dumpLayers := []dumpLayer{}
for _, layer := range packet.Layers() {
it := dumpLayer { LayerName : gopacket.GetLayerTypeMetadata(int(layer.LayerType())).Name,
Layer : layer }
dumpLayers = append(dumpLayers, it)
}
if !*prettyJson {
str, _ := json.Marshal(dumpLayers)
fmt.Println(string(str))
} else {
str, _ := json.MarshalIndent(dumpLayers, "", " ")
fmt.Println(string(str))
}
case "gopacket":
fmt.Println(packet)
}
}
func runWithPacketSource(packetSource *gopacket.PacketSource) {
for packet := range packetSource.Packets() {
if *plusOnly {
packetLayers := packet.Layers()
if len(packetLayers) == 0 {
continue
}
var plusLayer gopacket.Layer = nil
for _, layer := range packetLayers {
if layer.LayerType() == layers.LayerTypePLUS {
plusLayer = layer
break
}
}
if plusLayer == nil {
continue
}
dumpPacket(packet)
} else {
dumpPacket(packet)
}
}
}