Blame view

samples/bpf/sock_example.h 834 Bytes
b24413180   Greg Kroah-Hartman   License cleanup: ...
1
  /* SPDX-License-Identifier: GPL-2.0 */
3c731eba4   Alexei Starovoitov   bpf: mini eBPF li...
2
3
4
5
6
  #include <stdlib.h>
  #include <stdio.h>
  #include <linux/unistd.h>
  #include <unistd.h>
  #include <string.h>
3c731eba4   Alexei Starovoitov   bpf: mini eBPF li...
7
  #include <errno.h>
ee12996c9   Arnaldo Carvalho de Melo   samples/bpf sock_...
8
  #include <linux/if_ether.h>
03f4723ed   Alexei Starovoitov   samples: bpf: exa...
9
10
11
  #include <net/if.h>
  #include <linux/if_packet.h>
  #include <arpa/inet.h>
3c731eba4   Alexei Starovoitov   bpf: mini eBPF li...
12
  #include "libbpf.h"
9899694a7   Joe Stringer   samples/bpf: Move...
13
  static inline int open_raw_sock(const char *name)
03f4723ed   Alexei Starovoitov   samples: bpf: exa...
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  {
  	struct sockaddr_ll sll;
  	int sock;
  
  	sock = socket(PF_PACKET, SOCK_RAW | SOCK_NONBLOCK | SOCK_CLOEXEC, htons(ETH_P_ALL));
  	if (sock < 0) {
  		printf("cannot create raw socket
  ");
  		return -1;
  	}
  
  	memset(&sll, 0, sizeof(sll));
  	sll.sll_family = AF_PACKET;
  	sll.sll_ifindex = if_nametoindex(name);
  	sll.sll_protocol = htons(ETH_P_ALL);
  	if (bind(sock, (struct sockaddr *)&sll, sizeof(sll)) < 0) {
  		printf("bind to %s: %s
  ", name, strerror(errno));
  		close(sock);
  		return -1;
  	}
  
  	return sock;
  }