Count Packets per IP with an eBPF Hash Map
Count packets per source IPv4 address in an XDP program with a BPF hash map, then read and print the totals from a libbpf user-space program.

A counter in an array map tells you how much traffic arrived. A counter keyed by address tells you who sent it, which is the question you actually ask during a flood or a scan. The eBPF hash map is the structure for that: a kernel-resident table that an XDP program updates on every packet and a user-space process reads whenever it likes. This post builds the whole loop on Linux 6.12 with libbpf 1.5: a kernel program that counts packets per source IPv4 address, a user-space reader that prints the table, and the points where a hash map surprises people, namely insertion races, capacity and byte order.
The kernel side
The map key is the 32-bit source address and the value is a 64-bit counter. The program looks the key up; if it exists, it increments the counter atomically; if not, it inserts a new entry.
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 10240);
__type(key, __u32);
__type(value, __u64);
} pkt_count SEC(".maps");
SEC("xdp")
int count_per_ip(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;
__u32 src = ip->saddr;
__u64 *count = bpf_map_lookup_elem(&pkt_count, &src);
if (count) {
__sync_fetch_and_add(count, 1);
} else {
__u64 one = 1;
if (bpf_map_update_elem(&pkt_count, &src, &one, BPF_NOEXIST) < 0) {
/* another CPU inserted it first: look again and add */
count = bpf_map_lookup_elem(&pkt_count, &src);
if (count)
__sync_fetch_and_add(count, 1);
}
}
return XDP_PASS;
}
char LICENSE[] SEC("license") = "GPL";Three details deserve explanation.
The key is stored in network byte order. ip->saddr is the address exactly as it appears on the wire. The program never converts it, because the map only needs a consistent key. The conversion happens at print time in user space, where inet_ntop expects network order.
Insertion is the race. Two CPUs can receive packets from a new address at the same moment. Both look up, both miss, and both try to insert. BPF_NOEXIST makes the update fail with -EEXIST for the loser instead of overwriting the winner's count. The loser then looks the entry up again and adds one. Without BPF_NOEXIST, the second update would replace the first and lose a packet. The map's own bucket locks make each operation atomic, but the lookup-then-insert sequence is yours to order correctly.
Updating in place is atomic too. __sync_fetch_and_add on the value pointer compiles to an atomic add instruction. A plain *count += 1 compiles to a load, an add and a store, and two CPUs interleaving there lose increments.
Capacity is the other limit. max_entries is fixed at map creation. When the table is full, bpf_map_update_elem returns an error for new keys, and the program above silently skips counting them. An attacker who sends from millions of spoofed addresses can fill the map and blind your counter. The dedicated map type BPF_MAP_TYPE_LRU_HASH evicts the least recently used entry instead, which trades exact counts for a map that never fills. Use it when the table tracks an unbounded population such as arbitrary client addresses.
Pinning the map for user space
A user-space program needs a handle to the map. The simplest way is to pin the loaded maps in the BPF filesystem, using bpftool, which loads the object and attaches it in one go:
clang -O2 -g -target bpf -c ipcount.bpf.c -o ipcount.bpf.o
sudo mkdir -p /sys/fs/bpf/ipcount
sudo bpftool prog loadall ipcount.bpf.o /sys/fs/bpf/ipcount pinmaps /sys/fs/bpf/ipcount/maps
sudo bpftool net attach xdpdrv pinned /sys/fs/bpf/ipcount/count_per_ip dev eth0prog loadall loads every program in the object and pins each one under the given directory, named after its function. pinmaps pins each map under the second directory, named after the map, so the counter appears at /sys/fs/bpf/ipcount/maps/pkt_count. The bpftool net attach command then hooks the pinned program onto the interface in native mode.
The user-space reader
The reader opens the pinned map with bpf_obj_get and walks every key with bpf_map_get_next_key:
#include <arpa/inet.h>
#include <bpf/bpf.h>
#include <stdio.h>
int main(void)
{
int fd = bpf_obj_get("/sys/fs/bpf/ipcount/maps/pkt_count");
if (fd < 0) {
perror("bpf_obj_get");
return 1;
}
__u32 key, next;
int have_key = 0;
char text[INET_ADDRSTRLEN];
while (bpf_map_get_next_key(fd, have_key ? &key : NULL, &next) == 0) {
__u64 count;
if (bpf_map_lookup_elem(fd, &next, &count) == 0) {
inet_ntop(AF_INET, &next, text, sizeof(text));
printf("%-15s %llu\n", text, (unsigned long long)count);
}
key = next;
have_key = 1;
}
return 0;
}Build it with gcc ipcount.c -lbpf -o ipcount and run it as root. With three hosts sending traffic, the output looks like this, in the table's iteration order:
192.0.2.7 412
192.0.2.19 88
198.51.100.4 3The counts and the order will differ; hash tables do not iterate in insertion or numeric order. If you need a ranking, collect the entries into an array and sort in user space.
Walking a map while the program updates it is safe but not a snapshot. A key may be added or removed between get_next_key calls. If a key you just fetched is deleted before you call get_next_key with it, the iteration restarts from the first key, which can show duplicates. For a periodic report this is fine. For exact accounting, use bpf_map_lookup_batch, available since Linux 5.6, which reads many entries per syscall with better consistency.
Reading from the command line
For a quick look, skip the C program and ask bpftool:
sudo bpftool map dump pinned /sys/fs/bpf/ipcount/maps/pkt_countkey: c0 00 02 07 value: 9c 01 00 00 00 00 00 00
key: c0 00 02 13 value: 58 00 00 00 00 00 00 00
Found 2 elementsThe key c0 00 02 07 is 192.0.2.7 in network order, and the value bytes are little-endian: 0x019c is 412. Plain-text dumps like this make byte-order mistakes obvious.
Choosing the right counting granularity
Per-address counting is one of several levels, and the right one depends on what you will do with the numbers. Counting per source address answers who is talking, but it grows with the number of distinct senders. Counting per destination port answers what is being hit, and the key space is bounded at 65,536. Counting per protocol or per TCP flag combination is smaller still, and often enough to detect a SYN flood, because the signal is a shift in the ratio rather than the identity of any sender.
A practical pattern is to run two maps: a small, exact one for coarse categories that you always want, and an LRU hash for the long tail of addresses that you only need while they are active. The program updates both on each packet, which costs two lookups, but each lookup is a hash computation on a short key and stays well inside a modest instruction budget. Keep an eye on the verifier's complexity limit if you add many such branches, since each map access and each branch multiplies the states it must explore.
When you export the numbers, remember that counters from a hash map are cumulative since the entry was created. To turn them into rates, a user-space agent should sample on a fixed interval, remember the previous values and report the difference. If an entry disappears and returns, as happens with the LRU type, a negative difference means the entry was recreated, and the right response is to treat the new value as the delta rather than reporting a negative rate.
Resetting and resource limits
Counters only grow. To measure rates, read the table twice and subtract, or clear it between intervals with bpf_map_delete_elem. Memory is charged to the creating process's cgroup on kernels since 5.11, replacing the old RLIMIT_MEMLOCK accounting, so a large map can fail to create inside a constrained container even where it works on the host.
When not to use a hash map
If keys are small dense integers such as CPU numbers, an array map is simpler and faster.
If counters are updated by many CPUs on a few hot keys, use
BPF_MAP_TYPE_PERCPU_HASH, which gives each CPU its own value and removes the contention, at the cost of summing the per-CPU values when you read.If the key population is unbounded, use the LRU variant, as above.
If you need exact, lossless accounting under attack, sample or aggregate elsewhere; a fixed-size map is a place where an attacker can choose which entries you lose.

