MCPcopy Index your code
hub / github.com/cilium/ebpf / Example_socketELF

Function Example_socketELF

example_sock_elf_test.go:84–144  ·  view source on GitHub ↗

ExampleSocketELF demonstrates how to load an eBPF program from an ELF, and attach it to a raw socket.

()

Source from the content-addressed store, hash-verified

82// ExampleSocketELF demonstrates how to load an eBPF program from an ELF,
83// and attach it to a raw socket.
84func Example_socketELF() {
85 const SO_ATTACH_BPF = 50
86
87 index := flag.Int("index", 0, "specify ethernet index")
88 flag.Parse()
89
90 spec, err := ebpf.LoadCollectionSpecFromReader(bytes.NewReader(program[:]))
91 if err != nil {
92 panic(err)
93 }
94
95 var objs struct {
96 Prog *ebpf.Program `ebpf:"bpf_prog1"`
97 Stats *ebpf.Map `ebpf:"my_map"`
98 }
99
100 if err := spec.LoadAndAssign(&objs, nil); err != nil {
101 panic(err)
102 }
103 defer objs.Prog.Close()
104 defer objs.Stats.Close()
105
106 sock, err := openRawSock(*index)
107 if err != nil {
108 panic(err)
109 }
110 defer syscall.Close(sock)
111
112 if err := syscall.SetsockoptInt(sock, syscall.SOL_SOCKET, SO_ATTACH_BPF, objs.Prog.FD()); err != nil {
113 panic(err)
114 }
115
116 fmt.Printf("Filtering on eth index: %d\n", *index)
117 fmt.Println("Packet stats:")
118
119 for {
120 const (
121 ICMP = 0x01
122 TCP = 0x06
123 UDP = 0x11
124 )
125
126 time.Sleep(time.Second)
127 var icmp uint64
128 var tcp uint64
129 var udp uint64
130 err := objs.Stats.Lookup(uint32(ICMP), &icmp)
131 if err != nil {
132 panic(err)
133 }
134 err = objs.Stats.Lookup(uint32(TCP), &tcp)
135 if err != nil {
136 panic(err)
137 }
138 err = objs.Stats.Lookup(uint32(UDP), &udp)
139 if err != nil {
140 panic(err)
141 }

Callers

nothing calls this directly

Calls 7

openRawSockFunction · 0.85
IntMethod · 0.80
LoadAndAssignMethod · 0.80
CloseMethod · 0.65
FDMethod · 0.65
LookupMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…