|
| 1 | +// xdp_ip_map.c |
| 2 | +#include <linux/bpf.h> |
| 3 | +#include <bpf/bpf_helpers.h> |
| 4 | +#include <bpf/bpf_endian.h> |
| 5 | +#include <linux/if_ether.h> |
| 6 | +#include <linux/ip.h> |
| 7 | + |
| 8 | +struct ip_key { |
| 9 | + __u8 family; // 4 = IPv4 |
| 10 | + __u8 pad[3]; // padding for alignment |
| 11 | + __u8 addr[16]; // IPv4 uses first 4 bytes |
| 12 | +}; |
| 13 | + |
| 14 | +// key → packet count |
| 15 | +struct { |
| 16 | + __uint(type, BPF_MAP_TYPE_HASH); |
| 17 | + __uint(max_entries, 16384); |
| 18 | + __type(key, struct ip_key); |
| 19 | + __type(value, __u64); |
| 20 | +} ip_count_map SEC(".maps"); |
| 21 | + |
| 22 | +SEC("xdp") |
| 23 | +int xdp_ip_map(struct xdp_md *ctx) |
| 24 | +{ |
| 25 | + void *data_end = (void *)(long)ctx->data_end; |
| 26 | + void *data = (void *)(long)ctx->data; |
| 27 | + struct ethhdr *eth = data; |
| 28 | + |
| 29 | + if (eth + 1 > (struct ethhdr *)data_end) |
| 30 | + return XDP_PASS; |
| 31 | + |
| 32 | + __u16 h_proto = eth->h_proto; |
| 33 | + void *nh = data + sizeof(*eth); |
| 34 | + |
| 35 | + // VLAN handling: single tag |
| 36 | + if (h_proto == bpf_htons(ETH_P_8021Q) || |
| 37 | + h_proto == bpf_htons(ETH_P_8021AD)) { |
| 38 | + |
| 39 | + if (nh + 4 > data_end) |
| 40 | + return XDP_PASS; |
| 41 | + |
| 42 | + h_proto = *(__u16 *)(nh + 2); |
| 43 | + nh += 4; |
| 44 | + } |
| 45 | + |
| 46 | + struct ip_key key = {}; |
| 47 | + |
| 48 | + // IPv4 |
| 49 | + if (h_proto == bpf_htons(ETH_P_IP)) { |
| 50 | + struct iphdr *iph = nh; |
| 51 | + if (iph + 1 > (struct iphdr *)data_end) |
| 52 | + return XDP_PASS; |
| 53 | + |
| 54 | + key.family = 4; |
| 55 | + // Copy 4 bytes of IPv4 address |
| 56 | + __builtin_memcpy(key.addr, &iph->saddr, 4); |
| 57 | + |
| 58 | + __u64 *val = bpf_map_lookup_elem(&ip_count_map, &key); |
| 59 | + if (val) |
| 60 | + (*val)++; |
| 61 | + else { |
| 62 | + __u64 init = 1; |
| 63 | + bpf_map_update_elem(&ip_count_map, &key, &init, BPF_ANY); |
| 64 | + } |
| 65 | + |
| 66 | + return XDP_PASS; |
| 67 | + } |
| 68 | + |
| 69 | + return XDP_PASS; |
| 70 | +} |
| 71 | + |
| 72 | +char _license[] SEC("license") = "GPL"; |
0 commit comments