sockex1_user.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <stdio.h>
  3. #include <assert.h>
  4. #include <linux/bpf.h>
  5. #include <bpf/bpf.h>
  6. #include <bpf/libbpf.h>
  7. #include "sock_example.h"
  8. #include <unistd.h>
  9. #include <arpa/inet.h>
  10. int main(int ac, char **argv)
  11. {
  12. struct bpf_object *obj;
  13. int map_fd, prog_fd;
  14. char filename[256];
  15. int i, sock;
  16. FILE *f;
  17. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  18. if (bpf_prog_load(filename, BPF_PROG_TYPE_SOCKET_FILTER,
  19. &obj, &prog_fd))
  20. return 1;
  21. map_fd = bpf_object__find_map_fd_by_name(obj, "my_map");
  22. sock = open_raw_sock("lo");
  23. assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd,
  24. sizeof(prog_fd)) == 0);
  25. f = popen("ping -4 -c5 localhost", "r");
  26. (void) f;
  27. for (i = 0; i < 5; i++) {
  28. long long tcp_cnt, udp_cnt, icmp_cnt;
  29. int key;
  30. key = IPPROTO_TCP;
  31. assert(bpf_map_lookup_elem(map_fd, &key, &tcp_cnt) == 0);
  32. key = IPPROTO_UDP;
  33. assert(bpf_map_lookup_elem(map_fd, &key, &udp_cnt) == 0);
  34. key = IPPROTO_ICMP;
  35. assert(bpf_map_lookup_elem(map_fd, &key, &icmp_cnt) == 0);
  36. printf("TCP %lld UDP %lld ICMP %lld bytes\n",
  37. tcp_cnt, udp_cnt, icmp_cnt);
  38. sleep(1);
  39. }
  40. return 0;
  41. }