sockex1_user.c 979 B

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