github.com/cilium/ebpf@v0.15.1-0.20240517100537-8079b37aa138/docs/examples/getting_started/main.go (about)

     1  // getting_started_main {
     2  package main
     3  
     4  import (
     5  	"log"
     6  	"net"
     7  	"os"
     8  	"os/signal"
     9  	"time"
    10  
    11  	"github.com/cilium/ebpf/link"
    12  	"github.com/cilium/ebpf/rlimit"
    13  )
    14  
    15  func main() {
    16  	// Remove resource limits for kernels <5.11.
    17  	if err := rlimit.RemoveMemlock(); err != nil { // (1)!
    18  		log.Fatal("Removing memlock:", err)
    19  	}
    20  
    21  	// Load the compiled eBPF ELF and load it into the kernel.
    22  	var objs counterObjects // (2)!
    23  	if err := loadCounterObjects(&objs, nil); err != nil {
    24  		log.Fatal("Loading eBPF objects:", err)
    25  	}
    26  	defer objs.Close() // (3)!
    27  
    28  	ifname := "eth0" // Change this to an interface on your machine.
    29  	iface, err := net.InterfaceByName(ifname)
    30  	if err != nil {
    31  		log.Fatalf("Getting interface %s: %s", ifname, err)
    32  	}
    33  
    34  	// Attach count_packets to the network interface.
    35  	link, err := link.AttachXDP(link.XDPOptions{ // (4)!
    36  		Program:   objs.CountPackets,
    37  		Interface: iface.Index,
    38  	})
    39  	if err != nil {
    40  		log.Fatal("Attaching XDP:", err)
    41  	}
    42  	defer link.Close() // (5)!
    43  
    44  	log.Printf("Counting incoming packets on %s..", ifname)
    45  
    46  	// Periodically fetch the packet counter from PktCount,
    47  	// exit the program when interrupted.
    48  	tick := time.Tick(time.Second)
    49  	stop := make(chan os.Signal, 5)
    50  	signal.Notify(stop, os.Interrupt)
    51  	for {
    52  		select {
    53  		case <-tick:
    54  			var count uint64
    55  			err := objs.PktCount.Lookup(uint32(0), &count) // (6)!
    56  			if err != nil {
    57  				log.Fatal("Map lookup:", err)
    58  			}
    59  			log.Printf("Received %d packets", count)
    60  		case <-stop:
    61  			log.Print("Received signal, exiting..")
    62  			return
    63  		}
    64  	}
    65  }
    66  
    67  // }