-
Notifications
You must be signed in to change notification settings - Fork 1
/
pcapinput.go
48 lines (41 loc) · 1.01 KB
/
pcapinput.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
// Package pcapinput enables PCAP live capture or file reading.
package pcapinput
import (
"context"
"errors"
"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
)
// Error conditions.
var (
ErrNoInputConfig = errors.New("either device or filename must be specified")
)
// Config contains PCAP input options.
type Config struct {
Device string `json:"device,omitempty"`
SnapLen int `json:"snaplen,omitempty"`
Filename string `json:"filename,omitempty"`
}
// Open opens PCAP handle.
func Open(ctx context.Context, cfg Config) (source gopacket.PacketDataSource, e error) {
var hdl *pcap.Handle
switch {
case cfg.Device != "" && cfg.Filename == "":
if cfg.SnapLen <= 0 {
cfg.SnapLen = 9200
}
hdl, e = pcap.OpenLive(cfg.Device, int32(cfg.SnapLen), true, pcap.BlockForever)
case cfg.Filename != "" && cfg.Device == "":
hdl, e = pcap.OpenOffline(cfg.Filename)
default:
e = ErrNoInputConfig
}
if e != nil {
return nil, e
}
go func() {
<-ctx.Done()
hdl.Close()
}()
return hdl, nil
}