sockex3_user.c 1.9 KB

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