-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlinux.go
More file actions
77 lines (62 loc) · 1.38 KB
/
linux.go
File metadata and controls
77 lines (62 loc) · 1.38 KB
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
// +build linux
package gopcapnative
import (
"fmt"
"net"
"os"
"syscall"
)
const (
ETH_P_ALL_HTONS = 0x0300
)
func OpenLivePcap(device string) (*LivePcap, error) {
fd, err := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_RAW, ETH_P_ALL_HTONS)
if err != nil {
return nil, err
}
iface, err := net.InterfaceByName(device)
if err != nil {
return nil, err
}
sockAddr := syscall.SockaddrLinklayer{}
sockAddr.Ifindex = iface.Index
sockAddr.Protocol = ETH_P_ALL_HTONS
if err := syscall.Bind(fd, &sockAddr); err != nil {
return nil, err
}
f := os.NewFile(uintptr(fd), fmt.Sprintf("fd %d", fd))
result := &LivePcap{
device: device,
handle: fd,
file: f,
}
if err := result.SetBufferSize(65536); err != nil {
return nil, err
}
return result, nil
}
type LivePcap struct {
device string
handle int
file *os.File
bufferSize uint32
}
func (this *LivePcap) SetBufferSize(size uint32) error {
this.bufferSize = size
return syscall.SetsockoptInt(this.handle, syscall.SOL_SOCKET, syscall.SO_RCVBUF, int(size))
}
func (this *LivePcap) Read() ([][]byte, error) {
buffer := make([]byte, this.bufferSize)
n, err := this.file.Read(buffer)
if err != nil {
return nil, err
}
// CHECK: multiple packets possible?
return [][]byte{buffer[:n]}, nil
}
func (this *LivePcap) Close() {
if err := this.file.Close(); err != nil {
panic(err)
}
this.handle = -1
}