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