sockex2_user.c 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include <stdio.h>
  2. #include <assert.h>
  3. #include <linux/bpf.h>
  4. #include "libbpf.h"
  5. #include "bpf_load.h"
  6. #include "sock_example.h"
  7. #include <unistd.h>
  8. #include <arpa/inet.h>
  9. #include <sys/resource.h>
  10. struct pair {
  11. __u64 packets;
  12. __u64 bytes;
  13. };
  14. int main(int ac, char **argv)
  15. {
  16. struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY};
  17. char filename[256];
  18. FILE *f;
  19. int i, sock;
  20. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  21. setrlimit(RLIMIT_MEMLOCK, &r);
  22. if (load_bpf_file(filename)) {
  23. printf("%s", bpf_log_buf);
  24. return 1;
  25. }
  26. sock = open_raw_sock("lo");
  27. assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, prog_fd,
  28. sizeof(prog_fd[0])) == 0);
  29. f = popen("ping -c5 localhost", "r");
  30. (void) f;
  31. for (i = 0; i < 5; i++) {
  32. int key = 0, next_key;
  33. struct pair value;
  34. while (bpf_map_get_next_key(map_fd[0], &key, &next_key) == 0) {
  35. bpf_map_lookup_elem(map_fd[0], &next_key, &value);
  36. printf("ip %s bytes %lld packets %lld\n",
  37. inet_ntoa((struct in_addr){htonl(next_key)}),
  38. value.bytes, value.packets);
  39. key = next_key;
  40. }
  41. sleep(1);
  42. }
  43. return 0;
  44. }