File tree 3 files changed +23
-13
lines changed
3 files changed +23
-13
lines changed Original file line number Diff line number Diff line change 1
- xdp-bpf2go-example
1
+ xdp-bpf2go-example
2
+ ** bpfeb.go
3
+ ** bpfel.go
Original file line number Diff line number Diff line change @@ -14,6 +14,11 @@ import (
14
14
)
15
15
16
16
func main () {
17
+ // Check if running as root
18
+ if os .Geteuid () != 0 {
19
+ log .Fatal ("This program must be run as root!" )
20
+ }
21
+
17
22
// Remove resource limits for kernels <5.11.
18
23
if err := rlimit .RemoveMemlock (); err != nil {
19
24
log .Fatal ("Removing memlock:" , err )
@@ -26,7 +31,12 @@ func main() {
26
31
}
27
32
defer objs .Close ()
28
33
29
- ifname := "eno2" // Change this to an interface on your machine.
34
+ // Capture user input from command-line arguments
35
+ if len (os .Args ) < 2 {
36
+ log .Fatal ("Please provide a network interface name as an argument" )
37
+ }
38
+ ifname := os .Args [1 ] // Get the interface name from the first argument
39
+
30
40
iface , err := net .InterfaceByName (ifname )
31
41
if err != nil {
32
42
log .Fatalf ("Getting interface %s: %s" , ifname , err )
@@ -50,7 +60,6 @@ func main() {
50
60
for {
51
61
select {
52
62
case <- tick :
53
- // log.Print(objs.ProtocolCount)
54
63
printMap (objs .ProtocolCount )
55
64
if err != nil {
56
65
log .Fatal ("Map lookup:" , err )
Original file line number Diff line number Diff line change 4
4
#include <bpf/bpf_helpers.h>
5
5
#include <linux/if_ether.h>
6
6
#include <linux/ip.h>
7
+ #include <bpf/bpf_endian.h>
7
8
8
9
struct {
9
10
__uint (type , BPF_MAP_TYPE_ARRAY );
@@ -17,30 +18,28 @@ int get_packet_protocol(struct xdp_md *ctx) {
17
18
18
19
void * data_end = (void * )(long )ctx -> data_end ;
19
20
void * data = (void * )(long )ctx -> data ;
21
+ struct ethhdr * eth = data ;
22
+ struct iphdr * ip = data + sizeof (struct ethhdr );
23
+ __u32 key = ip -> protocol ; // Using IP protocol as the key
24
+ __u64 * count = bpf_map_lookup_elem (& protocol_count , & key );
20
25
21
26
// Parse Ethernet header
22
- struct ethhdr * eth = data ;
23
- if ((void * )(eth + 1 ) > data_end ) {
27
+ if ((void * )(eth + 1 ) > data_end )
24
28
return XDP_PASS ;
25
- }
26
29
27
30
// Check if the packet is an IP packet
28
- if (eth -> h_proto != __constant_htons (ETH_P_IP )) {
31
+ if (eth -> h_proto != bpf_htons (ETH_P_IP )) {
29
32
return XDP_PASS ;
30
33
}
31
34
32
35
// Parse IP header
33
- struct iphdr * ip = data + sizeof (struct ethhdr );
34
36
if ((void * )(ip + 1 ) > data_end ) {
35
37
return XDP_PASS ;
36
38
}
37
39
38
- __u32 key = ip -> protocol ; // Using IP protocol as the key
39
- __u64 * count = bpf_map_lookup_elem (& protocol_count , & key );
40
- if (count ) {
40
+ if (count )
41
41
__sync_fetch_and_add (count , 1 );
42
- }
43
-
42
+
44
43
return XDP_PASS ;
45
44
}
46
45
You can’t perform that action at this time.
0 commit comments