sockex2_user.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. struct pair {
  11. __u64 packets;
  12. __u64 bytes;
  13. };
  14. int main(int ac, char **argv)
  15. {
  16. struct bpf_program *prog;
  17. struct bpf_object *obj;
  18. int map_fd, prog_fd;
  19. char filename[256];
  20. int i, sock, err;
  21. FILE *f;
  22. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  23. obj = bpf_object__open_file(filename, NULL);
  24. if (libbpf_get_error(obj))
  25. return 1;
  26. prog = bpf_object__next_program(obj, NULL);
  27. bpf_program__set_type(prog, BPF_PROG_TYPE_SOCKET_FILTER);
  28. err = bpf_object__load(obj);
  29. if (err)
  30. return 1;
  31. prog_fd = bpf_program__fd(prog);
  32. map_fd = bpf_object__find_map_fd_by_name(obj, "hash_map");
  33. sock = open_raw_sock("lo");
  34. assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd,
  35. sizeof(prog_fd)) == 0);
  36. f = popen("ping -4 -c5 localhost", "r");
  37. (void) f;
  38. for (i = 0; i < 5; i++) {
  39. int key = 0, next_key;
  40. struct pair value;
  41. while (bpf_map_get_next_key(map_fd, &key, &next_key) == 0) {
  42. bpf_map_lookup_elem(map_fd, &next_key, &value);
  43. printf("ip %s bytes %lld packets %lld\n",
  44. inet_ntoa((struct in_addr){htonl(next_key)}),
  45. value.bytes, value.packets);
  46. key = next_key;
  47. }
  48. sleep(1);
  49. }
  50. return 0;
  51. }