ExampleSocketELF demonstrates how to load an eBPF program from an ELF, and attach it to a raw socket.
()
| 82 | // ExampleSocketELF demonstrates how to load an eBPF program from an ELF, |
| 83 | // and attach it to a raw socket. |
| 84 | func 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 | } |
nothing calls this directly
no test coverage detected
searching dependent graphs…