This repository has been archived by the owner on May 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.go
69 lines (57 loc) · 1.38 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
package main
import (
"fmt"
"syscall"
"time"
"golang.org/x/sys/unix"
)
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go counter counter.c -- -I./include -nostdinc -O3
func main() {
const SO_ATTACH_BPF = 50
const loopback = 1
err := unix.Setrlimit(unix.RLIMIT_MEMLOCK, &unix.Rlimit{
Cur: unix.RLIM_INFINITY,
Max: unix.RLIM_INFINITY,
})
if err != nil {
fmt.Println("WARNING: Failed to adjust rlimit")
}
specs, err := newCounterSpecs()
if err != nil {
panic(err)
}
objs, err := specs.Load(nil)
if err != nil {
panic(err)
}
defer objs.Close()
sock, err := openRawSock(loopback)
if err != nil {
panic(err)
}
defer syscall.Close(sock)
if err := syscall.SetsockoptInt(sock, syscall.SOL_SOCKET, SO_ATTACH_BPF, objs.ProgramCountPackets.FD()); err != nil {
panic(err)
}
for range time.Tick(time.Second) {
var count uint64
if err := objs.MapPackets.Lookup(uint32(0), &count); err != nil {
panic(err)
}
fmt.Println("Saw", count, "packets")
}
}
func openRawSock(index int) (int, error) {
const ETH_P_ALL uint16 = 0x300
sock, err := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_RAW|syscall.SOCK_NONBLOCK|syscall.SOCK_CLOEXEC, int(ETH_P_ALL))
if err != nil {
return 0, err
}
sll := syscall.SockaddrLinklayer{}
sll.Protocol = ETH_P_ALL
sll.Ifindex = index
if err := syscall.Bind(sock, &sll); err != nil {
return 0, err
}
return sock, nil
}