sockex3_user.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <stdio.h>
  3. #include <assert.h>
  4. #include <bpf/bpf.h>
  5. #include <bpf/libbpf.h>
  6. #include "sock_example.h"
  7. #include <unistd.h>
  8. #include <arpa/inet.h>
  9. struct flow_key_record {
  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. int i, sock, fd, main_prog_fd, hash_map_fd;
  25. struct bpf_program *prog;
  26. struct bpf_object *obj;
  27. char filename[256];
  28. FILE *f;
  29. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  30. obj = bpf_object__open_file(filename, NULL);
  31. if (libbpf_get_error(obj)) {
  32. fprintf(stderr, "ERROR: opening BPF object file failed\n");
  33. return 0;
  34. }
  35. /* load BPF program */
  36. if (bpf_object__load(obj)) {
  37. fprintf(stderr, "ERROR: loading BPF object file failed\n");
  38. goto cleanup;
  39. }
  40. hash_map_fd = bpf_object__find_map_fd_by_name(obj, "hash_map");
  41. if (hash_map_fd < 0) {
  42. fprintf(stderr, "ERROR: finding a map in obj file failed\n");
  43. goto cleanup;
  44. }
  45. /* find BPF main program */
  46. main_prog_fd = 0;
  47. bpf_object__for_each_program(prog, obj) {
  48. fd = bpf_program__fd(prog);
  49. if (!strcmp(bpf_program__name(prog), "main_prog"))
  50. main_prog_fd = fd;
  51. }
  52. if (main_prog_fd == 0) {
  53. fprintf(stderr, "ERROR: can't find main_prog\n");
  54. goto cleanup;
  55. }
  56. sock = open_raw_sock("lo");
  57. /* attach BPF program to socket */
  58. assert(setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &main_prog_fd,
  59. sizeof(__u32)) == 0);
  60. if (argc > 1)
  61. f = popen("ping -4 -c5 localhost", "r");
  62. else
  63. f = popen("netperf -l 4 localhost", "r");
  64. (void) f;
  65. for (i = 0; i < 5; i++) {
  66. struct flow_key_record key = {}, next_key;
  67. struct pair value;
  68. sleep(1);
  69. printf("IP src.port -> dst.port bytes packets\n");
  70. while (bpf_map_get_next_key(hash_map_fd, &key, &next_key) == 0) {
  71. bpf_map_lookup_elem(hash_map_fd, &next_key, &value);
  72. printf("%s.%05d -> %s.%05d %12lld %12lld\n",
  73. inet_ntoa((struct in_addr){htonl(next_key.src)}),
  74. next_key.port16[0],
  75. inet_ntoa((struct in_addr){htonl(next_key.dst)}),
  76. next_key.port16[1],
  77. value.bytes, value.packets);
  78. key = next_key;
  79. }
  80. }
  81. cleanup:
  82. bpf_object__close(obj);
  83. return 0;
  84. }