forked from bisrael8191/sniffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pcap.go
52 lines (44 loc) · 1.12 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
package main
import (
"fmt"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/pcap"
)
// libpcap version of the gopacket library
type PcapSniffer struct {
handle *pcap.Handle
}
func (s *PcapSniffer) Open(config *Config) error {
// Capture settings
const (
// Max packet length
snaplen int32 = 65536
// Set the interface in promiscuous mode
promisc bool = true
// Timeout duration
flushAfter string = "10s"
//BPF filter when capturing packets
filter string = "ip"
)
// Open the interface
flushDuration, err := time.ParseDuration(flushAfter)
if err != nil {
return fmt.Errorf("Invalid flush duration: %s", flushAfter)
}
handle, err := pcap.OpenLive(*iface, snaplen, promisc, flushDuration/2)
if err != nil {
return fmt.Errorf("Error opening pcap handle: %s", err)
}
if err := handle.SetBPFFilter(filter); err != nil {
return fmt.Errorf("Error setting BPF filter: %s", err)
}
s.handle = handle
return nil
}
func (s *PcapSniffer) Close() {
s.handle.Close()
}
func (s *PcapSniffer) ReadPacket() (data []byte, ci gopacket.CaptureInfo, err error) {
return s.handle.ZeroCopyReadPacketData()
}