test_probe_write_user_user.c 2.4 KB

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