forked from lizrice/ebpf-beginners
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpacket.py
More file actions
40 lines (32 loc) · 774 Bytes
/
packet.py
File metadata and controls
40 lines (32 loc) · 774 Bytes
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
#!/usr/bin/python
from bcc import BPF
from time import sleep
# Counts number of IP packets received per protocol on the eth0 interface
program = """
#include "packet.h"
BPF_HASH(packets);
int hello_packet(struct xdp_md *ctx) {
u64 counter = 0;
u64 key = 0;
u64 *p;
key = lookup_protocol(ctx);
if (key != 0) {
p = packets.lookup(&key);
if (p != 0) {
counter = *p;
}
counter++;
packets.update(&key, &counter);
}
return XDP_PASS;
}
"""
b = BPF(text=program)
b.attach_xdp(dev="eth0", fn=b.load_func("hello_packet",
BPF.XDP))
while True:
sleep(2)
s = ""
for k, v in b["packets"].items():
s += "Protocol {}: counter {},".format(k.value, v.value)
print(s)