sockex3_user.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 bpf_flow_keys {
  11. __be32 src;
  12. __be32 dst;
  13. union {
  14. __be32 ports;
  15. __be16 port16[2];
  16. };
  17. __u32 ip_proto;
  18. };
  19. struct pair {
  20. __u64 packets;
  21. __u64 bytes;
  22. };
  23. int main(int argc, char **argv)
  24. {
  25. struct rlimit r = {RLIM_INFINITY, RLIM_INFINITY};
  26. char filename[256];
  27. FILE *f;
  28. int i, sock;
  29. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  30. setrlimit(RLIMIT_MEMLOCK, &r);
  31. if (load_bpf_file(filename)) {
  32. printf("%s", bpf_log_buf);
  33. return 1;
  34. }
  35. sock = open_raw_sock("lo");
  36. assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd[4],
  37. sizeof(__u32)) == 0);
  38. if (argc > 1)
  39. f = popen("ping -c5 localhost", "r");
  40. else
  41. f = popen("netperf -l 4 localhost", "r");
  42. (void) f;
  43. for (i = 0; i < 5; i++) {
  44. struct bpf_flow_keys key = {}, next_key;
  45. struct pair value;
  46. sleep(1);
  47. printf("IP src.port -> dst.port bytes packets\n");
  48. while (bpf_map_get_next_key(map_fd[2], &key, &next_key) == 0) {
  49. bpf_map_lookup_elem(map_fd[2], &next_key, &value);
  50. printf("%s.%05d -> %s.%05d %12lld %12lld\n",
  51. inet_ntoa((struct in_addr){htonl(next_key.src)}),
  52. next_key.port16[0],
  53. inet_ntoa((struct in_addr){htonl(next_key.dst)}),
  54. next_key.port16[1],
  55. value.bytes, value.packets);
  56. key = next_key;
  57. }
  58. }
  59. return 0;
  60. }