Gistrec

Управление ресурсами в ВЧ 8

May 14th, 2019
359
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 4.79 KB | None | 0 0
  1. /**
  2.  * Клиент
  3.  */
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <assert.h>
  7. #include <sys/socket.h>
  8. #include <netinet/in.h>
  9. #include <arpa/inet.h> /** inet_addr() */
  10.  
  11.  
  12. #define SERVER_PORT 8080
  13. #define CLIENT_PORT 8000
  14.  
  15.  
  16. int main() {
  17.     // Создаем сокет IPPROTO_IP
  18.     int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  19.     assert(sockfd != -1 && "Error: can't create socket");
  20.     printf("Socket created\n");
  21.  
  22.     // Создаем локальный адрес
  23.     struct sockaddr_in local_addr = {
  24.             .sin_family = AF_INET,
  25.             .sin_port   = htons(CLIENT_PORT),
  26.             .sin_addr   = { .s_addr = INADDR_ANY }
  27.     };
  28.  
  29.     int enable = 1;
  30.     setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
  31.  
  32.     // Биндим сокет
  33.     int result = bind(sockfd, (struct sockaddr *) &local_addr ,sizeof(struct sockaddr_in));
  34.     assert(result != -1 && "Error: can't bind socket");
  35.     printf("Socket binded\n");
  36.  
  37.     // Создаем адрес сервера
  38.     struct sockaddr_in remote_addr = {
  39.             .sin_family = AF_INET,
  40.             .sin_port   = htons(SERVER_PORT),
  41.             .sin_addr   = { .s_addr = inet_addr("127.0.0.1") },
  42.     };
  43.  
  44.     result = connect(sockfd, (sockaddr*) &remote_addr, sizeof(remote_addr));
  45.     assert(result != -1 && "Error: can't connect to server");
  46.     printf("Connected to server\n");
  47.  
  48.     char buf[256];
  49.  
  50.     while (true) {
  51.         // Запрашиваем пароль
  52.         printf("Введите команду: ");
  53.         fflush(stdout);
  54.         //scanf("%s", buf);
  55.         fgets(buf, 256, stdin);
  56.  
  57.         // Отправляем пароль на сервер
  58.         send(sockfd, buf, strlen(buf), 0);
  59.  
  60.         // Получаем ответ
  61.         int length = recv(sockfd, buf, sizeof(buf), 0);
  62.         assert(length != -1 && "Error: can't receive message");
  63.  
  64.         buf[length] = '\0';
  65.         printf("%s\n\n", buf);
  66.     }
  67.  
  68.     return 0;
  69. }
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85. /**
  86.  * Server.cpp
  87.  */
  88. #include <stdio.h>
  89. #include <unistd.h>
  90. #include <netinet/in.h>
  91. #include <sys/socket.h>
  92.  
  93.  
  94. #include <stdlib.h>
  95. #include <string.h>
  96. #include <assert.h>
  97.  
  98.  
  99. #define PID_CHILD 0
  100.  
  101. #define SERVER_PORT 8080
  102. #define CLIENT_PORT 8000
  103.  
  104. const char password[] = "aabbcc";
  105.  
  106. #include <unistd.h>
  107. #include <cstdlib>
  108. #include <fcntl.h>
  109. #include <signal.h>
  110.  
  111. void execute(char* cmd, char* output) {
  112.     int console = dup(1); // Делаем бекап STDOUT
  113.  
  114.     int pd[2];     //
  115.     pipe(pd);      // Заменяем STDOUT на созданный пайп
  116.     dup2(pd[1],1); //
  117.     dup2(pd[1],2); //
  118.  
  119.     // Вызываем команду
  120.     int retValue = system(cmd);
  121.     read(pd[0], output, 500);
  122.  
  123.     dup2(console, 1); // Восстанавливаем STDOUT
  124. }
  125.  
  126. /**
  127.  * Функция, в которой будут ожидаться сообщения от клиента
  128.  * @param clientfd - сокет клиента
  129.  */
  130. void listenClient(int clientfd) {
  131.     printf("Клиент подключился\n");
  132.     char buf[256];
  133.  
  134.     while (true) {
  135.         int length = recv(clientfd, buf, sizeof(buf), 0);
  136.         if (length <= 0) {
  137.             printf("Клиент отключился\n");
  138.             return;
  139.         }
  140.         buf[length] = '\0';
  141.  
  142.         char output[500] = { 0 };
  143.         execute(buf, output);
  144.         send(clientfd, output, strlen(output) - 1, 0);
  145.     }
  146. }
  147.  
  148.  
  149. int main() {
  150.     // Создаем сокет
  151.     int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  152.     assert(sockfd != -1 && "Error: can't create socket");
  153.     printf("Socket created\n");
  154.  
  155.     // Создаем локальный адрес
  156.     struct sockaddr_in local_addr = {
  157.             .sin_family = AF_INET,
  158.             .sin_port = htons(SERVER_PORT),
  159.             .sin_addr = { .s_addr = INADDR_ANY }
  160.     };
  161.  
  162.     int enable = 1;
  163.     setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int));
  164.  
  165.     // Биндим сокет
  166.     int result = bind(sockfd, (struct sockaddr *) &local_addr, sizeof(local_addr));
  167.     assert(result != -1 && "Error: can't bind socket");
  168.     printf("Socket binded\n");
  169.  
  170.     while (true) {
  171.         // Ожидаем подключение нового клиента
  172.         result = listen(sockfd, 5);
  173.         assert(result != -1 && "Error: can't listen socket");
  174.  
  175.         struct sockaddr_in client_addr = { 0 };
  176.         socklen_t addr_len = sizeof(client_addr);
  177.  
  178.         int clientfd = accept(sockfd, (sockaddr *) &client_addr, &addr_len);
  179.         assert(result != -1 && "Error: can't accept connection");
  180.  
  181.         int pid = fork();
  182.         assert(pid != -1 && "Error: can't create child process");
  183.         if (pid == PID_CHILD) {
  184.             listenClient(clientfd);
  185.             return 0;
  186.         }
  187.     }
  188. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment