sockex3_user.c 1.9 KB

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