sockex3_user.c 1.3 KB

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