Skip to content

Instantly share code, notes, and snippets.

@swananan
Last active June 16, 2025 08:01
Show Gist options
  • Select an option

  • Save swananan/7cf3162c717059ecb0bb9b5ebb5f4c4b to your computer and use it in GitHub Desktop.

Select an option

Save swananan/7cf3162c717059ecb0bb9b5ebb5f4c4b to your computer and use it in GitHub Desktop.
xdp_random_drop1%
from bcc import BPF
import sys
import time
if len(sys.argv) != 2:
print(f"Usage: {sys.argv[0]} <network-interface>")
sys.exit(1)
device = sys.argv[1]
bpf_program = """
#include <uapi/linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
int xdp_drop_random(struct xdp_md *ctx) {
u32 hash = bpf_get_prandom_u32();
if (hash % 100 == 0) {
return XDP_DROP;
}
return XDP_PASS;
}
"""
b = BPF(text=bpf_program)
fn = b.load_func("xdp_drop_random", BPF.XDP)
b.attach_xdp(device, fn, 0)
print(f"XDP random drop enabled on {device}. Dropping ~1% of packets. Press Ctrl+C to stop.")
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
print("Removing XDP program...")
b.remove_xdp(device, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment