Skip to content
systemcoding.dev
Networking

Write Your First XDP Program to Drop Packets

Write, compile and attach an XDP program in C that drops UDP packets for one port, with the bounds checks the verifier demands and a test you can run.

7 min read
Summarize in AI
Flat illustration of network packets crossing between two hosts, with the C, Rust and Linux logos.

The quickest way to understand XDP is to make it do something visible: stop a class of traffic before the kernel sees it. This post builds a program that drops every IPv4 UDP datagram addressed to port 9999 and passes everything else. Along the way it shows the pattern that every XDP program shares, parse headers while checking bounds at each step, and it uses clang 18, iproute2 6.x and Linux 6.12. If the hook and the verdicts are new to you, read what XDP is and where it runs first; this post assumes the program-and-verifier vocabulary of eBPF.

The parsing pattern

XDP gives you ctx->data and ctx->data_end, two addresses delimiting the frame. Before you read a header at some position, you must prove to the verifier that the whole header lies before data_end. The idiom is the same for every layer:

c
struct ethhdr *eth = data;
if ((void *)(eth + 1) > data_end)
    return XDP_PASS;

eth + 1 points one byte past the Ethernet header. If that is beyond the end, the frame is too short to hold one, and the program bails out. The verifier tracks this comparison and, on the branch where it passed, allows reads inside the header. Skip it and the program is rejected at load time, as the dedicated verifier-error post in this cluster shows.

The next header starts where the previous ended, so you chain the checks: Ethernet, then IPv4, then UDP. IPv4 headers vary in length because of options, which means the UDP header position depends on the ihl field, the header length in 32-bit words.

The complete program

drop_udp.bpf.cc
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/udp.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

#define BLOCKED_PORT 9999

SEC("xdp")
int drop_udp_9999(struct xdp_md *ctx)
{
    void *data = (void *)(long)ctx->data;
    void *data_end = (void *)(long)ctx->data_end;

    struct ethhdr *eth = data;
    if ((void *)(eth + 1) > data_end)
        return XDP_PASS;

    if (eth->h_proto != bpf_htons(ETH_P_IP))
        return XDP_PASS;

    struct iphdr *ip = (void *)(eth + 1);
    if ((void *)(ip + 1) > data_end)
        return XDP_PASS;

    if (ip->protocol != IPPROTO_UDP)
        return XDP_PASS;

    __u32 ip_len = ip->ihl * 4;
    if (ip_len < sizeof(*ip))
        return XDP_PASS;

    struct udphdr *udp = (void *)ip + ip_len;
    if ((void *)(udp + 1) > data_end)
        return XDP_PASS;

    if (udp->dest == bpf_htons(BLOCKED_PORT))
        return XDP_DROP;

    return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";

Walk through the decisions, because each one is deliberate.

  • The cast (void *)(long)ctx->data is required: the fields are 32-bit integers in the UAPI struct, and the verifier rewrites them into real pointers at load time.

  • Short or non-IP frames return XDP_PASS, not XDP_DROP. A filter that cannot understand a packet should leave it for the stack, otherwise ARP, IPv6 and VLAN-tagged traffic vanish. This program does not handle VLAN tags or IPv6, and the post's boundary section returns to that.

  • ip->ihl * 4 is the real header length. The check ip_len < sizeof(*ip) rejects a malformed ihl below 5, and it also gives the verifier a lower bound. The upper bound of 60 comes from ihl being a four-bit field.

  • Ports in headers are in network byte order, so the comparison uses bpf_htons(9999), which the compiler folds into a constant.

Fragmentation is another gap. A fragment after the first carries no UDP header, so reading udp->dest there reads payload bytes. Production code checks ip->frag_off and passes non-first fragments. This program does not, which is acceptable for a first example and worth knowing.

Compile and attach

Shell
clang -O2 -g -target bpf -c drop_udp.bpf.c -o drop_udp.bpf.o
sudo ip link set dev eth0 xdpdrv obj drop_udp.bpf.o sec xdp

-O2 matters: the verifier handles optimized code best, and unoptimized builds often fail on stack use or on bounds information the compiler would have simplified. -g adds debug and BTF information, which bpftool uses for readable dumps. The attach command uses xdpdrv to force native mode; if your interface driver lacks it, substitute xdpgeneric for development and remember the performance caveat.

Confirm the program loaded:

Shell
sudo bpftool prog show name drop_udp_9999
Text
87: xdp  name drop_udp_9999  tag 6f0c2d3a4b5e7c81  gpl
	loaded_at 2026-11-23T10:15:02+0000  uid 0

The id, tag and time are examples; yours will differ. A line like this is your sign the verifier accepted the object.

Test it

You need a second machine, or a second network namespace, to send traffic into the interface, because XDP sees only packets that arrive on it. From another host:

Shell
echo "hello" | nc -u -w1 192.0.2.10 9999
echo "hello" | nc -u -w1 192.0.2.10 9998

On the target, listen on both ports with nc -u -l 9999 and nc -u -l 9998 in separate terminals. The datagram to 9998 appears, and the one to 9999 never does, because it is discarded in the driver before the stack can deliver it to the listener. tcpdump on the target will not show the 9999 packet either, since a frame dropped in native mode never reaches the paths that feed packet taps. The evidence is the silence at the listener, and a counter map, which the per-IP counting post in this cluster adds, gives you a number to look at.

To detach:

Shell
sudo ip link set dev eth0 xdp off

What the verifier needs from you

If you delete the check if ((void *)(udp + 1) > data_end), loading fails with a message of this form:

Text
invalid access to packet, off=34 size=2, R1(id=0,off=34,r=20)

The message says: you tried to read two bytes at offset 34 of the packet, but the verified range r extends only to 20. The numbers depend on your layout, and the dedicated post on this error walks through reading them.

Handling VLAN tags and fragments

Two small additions make the filter behave on real networks. Frames on a trunk port or a VLAN-aware bridge carry an 802.1Q tag between the Ethernet source address and the real EtherType, so eth->h_proto equals ETH_P_8021Q and the IPv4 header sits four bytes further on. The program above passes those frames untouched, which is safe but means the filter never blocks tagged traffic. To handle a single tag you read the four-byte struct vlan_hdr after the Ethernet header, check its bounds, and continue with the encapsulated protocol field. Stacked tags need a small bounded loop, and the verifier insists that the loop count be a compile-time constant.

Fragments are the second gap. The IPv4 frag_off field holds the fragment offset in its low 13 bits and the more-fragments flag in a high bit. Only the first fragment, with offset zero, contains the UDP header. Add this check before reading the UDP header and pass anything with a non-zero offset:

c
if (ip->frag_off & bpf_htons(0x1FFF))
    return XDP_PASS;

The mask 0x1FFF selects the offset bits. A datagram split into fragments will then have its first fragment evaluated by the port rule and the rest passed, which means a blocked datagram may be dropped only in part, and the receiving stack will time out waiting for the missing pieces. For a strict block, drop every fragment that belongs to a flow you want gone, or, better, configure the host not to accept fragmented traffic on that service at all.

Reading what the compiler produced

When a program fails to load, or you want to know why it is as large as it is, dump the translated instructions. bpftool prog dump xlated name drop_udp_9999 prints the bytecode after verification, and bpftool prog dump jited name drop_udp_9999 prints the native machine code the JIT produced. Comparing the two on a small program is a good way to see that the bounds checks are a few comparisons and branches, not a runtime library. It also shows why the compiler flags matter: the same C compiled without optimization produces extra stack traffic that the verifier may refuse.

When not to write it this way

  • If you need IPv6 or VLAN support, add the extra parsing; a single-protocol filter silently ignores the others.

  • If you want counters, add a map; dropping with no visibility is hard to operate.

  • If many ports or addresses must be blocked, do not recompile for each; load the set into a hash map that user space updates.

  • If you are on a shared host with no attach privilege, use a socket filter or nftables instead, since XDP needs CAP_NET_ADMIN and CAP_BPF.

Share

Keep reading

Flat illustration of a microcontroller wired to an LED and a sensor, with the Bluetooth, Nordic Semiconductor and Arm logos.
Embedded

Create a Custom BLE GATT Service on nRF52

Define a custom 128-bit GATT service on nRF52 with Zephyr: characteristic properties, read and write callbacks, notifications through the CCC and MTU limits.

9 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.