Created
April 10, 2024 21:41
-
-
Save callowaysutton/72539e23cbb0f5620d8789c9676a1f62 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <linux/bpf.h> | |
#include <bpf/bpf_helpers.h> | |
// Define a per-CPU array map to keep the packet count | |
struct { | |
__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); | |
__uint(key_size, sizeof(__u32)); | |
__uint(value_size, sizeof(__u64)); | |
__uint(max_entries, 1); | |
} packet_count SEC(".maps"); | |
SEC("xdp") | |
int count_packets(struct xdp_md *ctx) { | |
__u32 key = 0; // Single key, since we have only one entry | |
__u64 init_val = 0; | |
__u64 *value; | |
// Look up the value of the packet count for the given key | |
value = bpf_map_lookup_elem(&packet_count, &key); | |
if (value) { | |
// Increment the packet count | |
*value += 1; | |
} else { | |
// Initialize the packet count if not found (though this should not happen with PERCPU_ARRAY) | |
bpf_map_update_elem(&packet_count, &key, &init_val, BPF_ANY); | |
} | |
return XDP_PASS; // Allow the packet to pass through | |
} | |
char _license[] SEC("license") = "GPL"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment