test_probe_write_user_user.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <stdio.h>
  3. #include <assert.h>
  4. #include <linux/bpf.h>
  5. #include <unistd.h>
  6. #include <bpf/bpf.h>
  7. #include "bpf_load.h"
  8. #include <sys/socket.h>
  9. #include <string.h>
  10. #include <netinet/in.h>
  11. #include <arpa/inet.h>
  12. int main(int ac, char **argv)
  13. {
  14. int serverfd, serverconnfd, clientfd;
  15. socklen_t sockaddr_len;
  16. struct sockaddr serv_addr, mapped_addr, tmp_addr;
  17. struct sockaddr_in *serv_addr_in, *mapped_addr_in, *tmp_addr_in;
  18. char filename[256];
  19. char *ip;
  20. serv_addr_in = (struct sockaddr_in *)&serv_addr;
  21. mapped_addr_in = (struct sockaddr_in *)&mapped_addr;
  22. tmp_addr_in = (struct sockaddr_in *)&tmp_addr;
  23. snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
  24. if (load_bpf_file(filename)) {
  25. printf("%s", bpf_log_buf);
  26. return 1;
  27. }
  28. assert((serverfd = socket(AF_INET, SOCK_STREAM, 0)) > 0);
  29. assert((clientfd = socket(AF_INET, SOCK_STREAM, 0)) > 0);
  30. /* Bind server to ephemeral port on lo */
  31. memset(&serv_addr, 0, sizeof(serv_addr));
  32. serv_addr_in->sin_family = AF_INET;
  33. serv_addr_in->sin_port = 0;
  34. serv_addr_in->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  35. assert(bind(serverfd, &serv_addr, sizeof(serv_addr)) == 0);
  36. sockaddr_len = sizeof(serv_addr);
  37. assert(getsockname(serverfd, &serv_addr, &sockaddr_len) == 0);
  38. ip = inet_ntoa(serv_addr_in->sin_addr);
  39. printf("Server bound to: %s:%d\n", ip, ntohs(serv_addr_in->sin_port));
  40. memset(&mapped_addr, 0, sizeof(mapped_addr));
  41. mapped_addr_in->sin_family = AF_INET;
  42. mapped_addr_in->sin_port = htons(5555);
  43. mapped_addr_in->sin_addr.s_addr = inet_addr("255.255.255.255");
  44. assert(!bpf_map_update_elem(map_fd[0], &mapped_addr, &serv_addr, BPF_ANY));
  45. assert(listen(serverfd, 5) == 0);
  46. ip = inet_ntoa(mapped_addr_in->sin_addr);
  47. printf("Client connecting to: %s:%d\n",
  48. ip, ntohs(mapped_addr_in->sin_port));
  49. assert(connect(clientfd, &mapped_addr, sizeof(mapped_addr)) == 0);
  50. sockaddr_len = sizeof(tmp_addr);
  51. ip = inet_ntoa(tmp_addr_in->sin_addr);
  52. assert((serverconnfd = accept(serverfd, &tmp_addr, &sockaddr_len)) > 0);
  53. printf("Server received connection from: %s:%d\n",
  54. ip, ntohs(tmp_addr_in->sin_port));
  55. sockaddr_len = sizeof(tmp_addr);
  56. assert(getpeername(clientfd, &tmp_addr, &sockaddr_len) == 0);
  57. ip = inet_ntoa(tmp_addr_in->sin_addr);
  58. printf("Client's peer address: %s:%d\n",
  59. ip, ntohs(tmp_addr_in->sin_port));
  60. /* Is the server's getsockname = the socket getpeername */
  61. assert(memcmp(&serv_addr, &tmp_addr, sizeof(struct sockaddr_in)) == 0);
  62. return 0;
  63. }