Debian Codegraph @

examples/xdp/main.go

raw symbols SCIP
1 //go:build linux
2
3 // This program demonstrates attaching an eBPF program to a network interface
4 // with XDP (eXpress Data Path). The program parses the IPv4 source address
5 // from packets and writes the packet count by IP to an LRU hash map.
6 // The userspace program (Go code in this file) prints the contents
7 // of the map to stdout every second.
8 // It is possible to modify the XDP program to drop or redirect packets
9 // as well -- give it a try!
10 // This example depends on bpf_link, available in Linux kernel version 5.7 or newer.
11 package main
12
13 import (
14 "fmt"
15 "log"
16 "net"
17 "net/netip"
18 "os"
19 "strings"
20 "time"
21
22 "github.com/cilium/ebpf"
23 "github.com/cilium/ebpf/link"
24 )
25
26 //go:generate go tool bpf2go -tags linux bpf xdp.c -- -I../headers
27
28 func main() {
29 if len(os.Args) < 2 {
30 log.Fatalf("Please specify a network interface")
31 }
32
33 // Look up the network interface by name.
34 ifaceName := os.Args[1]
35 iface, err := net.InterfaceByName(ifaceName)
36 if err != nil {
37 log.Fatalf("lookup network iface %q: %s", ifaceName, err)
38 }
39
40 // Load pre-compiled programs into the kernel.
41 objs := bpfObjects{}
42 if err := loadBpfObjects(&objs, nil); err != nil {
43 log.Fatalf("loading objects: %s", err)
44 }
45 defer objs.Close()
46
47 // Attach the program.
48 l, err := link.AttachXDP(link.XDPOptions{
49 Program: objs.XdpProgFunc,
50 Interface: iface.Index,
51 })
52 if err != nil {
53 log.Fatalf("could not attach XDP program: %s", err)
54 }
55 defer l.Close()
56
57 log.Printf("Attached XDP program to iface %q (index %d)", iface.Name, iface.Index)
58 log.Printf("Press Ctrl-C to exit and remove the program")
59
60 // Print the contents of the BPF hash map (source IP address -> packet count).
61 ticker := time.NewTicker(1 * time.Second)
62 defer ticker.Stop()
63 for range ticker.C {
64 s, err := formatMapContents(objs.XdpStatsMap)
65 if err != nil {
66 log.Printf("Error reading map: %s", err)
67 continue
68 }
69 log.Printf("Map contents:\n%s", s)
70 }
71 }
72
73 func formatMapContents(m *ebpf.Map) (string, error) {
74 var (
75 sb strings.Builder
76 key netip.Addr
77 val uint32
78 )
79 iter := m.Iterate()
80 for iter.Next(&key, &val) {
81 sourceIP := key // IPv4 source address in network byte order.
82 packetCount := val
83 sb.WriteString(fmt.Sprintf("\t%s => %d\n", sourceIP, packetCount))
84 }
85 return sb.String(), iter.Err()
86 }