forked from tadamra/gopacket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
capture.go
53 lines (45 loc) · 1.28 KB
/
capture.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
// Copyright 2012 Google, Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the LICENSE file in the root of the source
// tree.
// +build linux
package pcapgo
import (
"net"
"syscall"
"time"
"github.com/google/gopacket"
"github.com/mdlayher/raw"
)
// EthernetHandle wraps a raw.Conn, implementing gopacket.PacketDataSource so
// that the handle can be used with gopacket.NewPacketSource.
type EthernetHandle struct {
*raw.Conn
}
// ReadPacketData implements gopacket.PacketDataSource.
func (h *EthernetHandle) ReadPacketData() ([]byte, gopacket.CaptureInfo, error) {
b := make([]byte, 4096) // TODO(correctness): how much space do we need?
n, _, err := h.ReadFrom(b)
if err != nil {
return nil, gopacket.CaptureInfo{}, err
}
data := b[:n]
return data, gopacket.CaptureInfo{
CaptureLength: len(data),
Length: len(data),
Timestamp: time.Now(),
}, nil
}
// NewEthernetHandle implements pcap.OpenLive for ethernet interfaces only.
func NewEthernetHandle(ifname string) (*EthernetHandle, error) {
intf, err := net.InterfaceByName(ifname)
if err != nil {
return nil, err
}
conn, err := raw.ListenPacket(intf, syscall.ETH_P_ALL, nil)
if err != nil {
return nil, err
}
return &EthernetHandle{conn}, nil
}