sockex2_user.c 965 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. struct pair {
  9. __u64 packets;
  10. __u64 bytes;
  11. };
  12. int main(int ac, char **argv)
  13. {
  14. char filename[256];
  15. FILE *f;
  16. int i, sock;
  17. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  18. if (load_bpf_file(filename)) {
  19. printf("%s", bpf_log_buf);
  20. return 1;
  21. }
  22. sock = open_raw_sock("lo");
  23. assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, prog_fd,
  24. sizeof(prog_fd[0])) == 0);
  25. f = popen("ping -c5 localhost", "r");
  26. (void) f;
  27. for (i = 0; i < 5; i++) {
  28. int key = 0, next_key;
  29. struct pair value;
  30. while (bpf_get_next_key(map_fd[0], &key, &next_key) == 0) {
  31. bpf_lookup_elem(map_fd[0], &next_key, &value);
  32. printf("ip %s bytes %lld packets %lld\n",
  33. inet_ntoa((struct in_addr){htonl(next_key)}),
  34. value.bytes, value.packets);
  35. key = next_key;
  36. }
  37. sleep(1);
  38. }
  39. return 0;
  40. }