Advertisement
VladimirKostovsky

Osi_Lab2_serverWin_to_ethernet

Dec 18th, 2023 (edited)
843
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 10.74 KB | None | 0 0
  1. #include <winsock2.h>
  2. #include <iostream>
  3. #include <sstream>
  4. #include <string>
  5. #include <fstream>
  6. #include <locale>
  7. #include <vector>
  8. #include <algorithm>
  9.  
  10.  
  11. #pragma warning(disable: 4996)
  12. #pragma comment(lib, "Ws2_32.lib")
  13.  
  14. using namespace std;
  15.  
  16. void insertServerInfo(char* text, size_t bufferSize, const char* serverIP, int serverPort)
  17. {
  18.     // Create a string stream to manipulate the text
  19.     ostringstream oss;
  20.  
  21.     // Append the original text to the stream
  22.     oss << text << " Server IP: " << serverIP << ", Port: " << serverPort;
  23.  
  24.     // Get the resulting string
  25.     std::string result = oss.str();
  26.  
  27.     // Ensure the result fits into the buffer
  28.     if (result.length() < bufferSize - 1) // Account for null terminator
  29.     {
  30.         // Copy the modified text back to the original buffer
  31.         strncpy_s(text, bufferSize, result.c_str(), _TRUNCATE);
  32.  
  33.         // Null-terminate the buffer
  34.         text[bufferSize - 1] = '\0';
  35.     }
  36.     else
  37.     {
  38.         cerr << "Modified text exceeds the buffer size. Handle this case accordingly." << endl;
  39.     }
  40. }
  41. void handleClient(SOCKET clientSock, const sockaddr_in& sin)
  42. {
  43.     int retVal;
  44.  
  45.     do
  46.     {
  47.         char szReq[512];
  48.         retVal = recv(clientSock, szReq, sizeof(szReq) - 1, 0);
  49.  
  50.         if (retVal == SOCKET_ERROR)
  51.         {
  52.             cerr << "Failed to receive data. Error: " << WSAGetLastError() << endl;
  53.             closesocket(clientSock);
  54.             return;
  55.         }
  56.  
  57.         if (retVal == 0)
  58.         {
  59.             cout << "Client disconnected" << endl;
  60.             closesocket(clientSock);
  61.             return;
  62.         }
  63.  
  64.         szReq[retVal] = '\0';
  65.         cout << "Data received: " << szReq << endl;
  66.  
  67.         // Save user input to a text file
  68.         ofstream userInputFile("user_input.txt", ios::app); // Open the file in append mode
  69.  
  70.         if (userInputFile.is_open())
  71.         {
  72.             userInputFile << szReq << endl;
  73.             userInputFile.close();
  74.             cout << "User input saved to user_input.txt" << endl;
  75.         }
  76.         else
  77.         {
  78.             cerr << "Failed to open user_input.txt for writing." << endl;
  79.         }
  80.  
  81.         // Insert server info into the user input
  82.         insertServerInfo(szReq, sizeof(szReq), inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
  83.  
  84.         cout << "Sending response from the server" << endl;
  85.         retVal = send(clientSock, szReq, strlen(szReq), 0);
  86.  
  87.         if (retVal == SOCKET_ERROR)
  88.         {
  89.             cerr << "Failed to send data. Error: " << WSAGetLastError() << endl;
  90.             closesocket(clientSock);
  91.             return;
  92.         }
  93.  
  94.         ifstream outputFile("output.txt");
  95.         if (outputFile.is_open())
  96.         {
  97.             string line;
  98.             while (getline(outputFile, line))
  99.             {
  100.                 cout << line << endl;
  101.             }
  102.             outputFile.close();
  103.         }
  104.         else
  105.         {
  106.             cerr << "Failed to open the file for reading." << endl;
  107.         }
  108.  
  109.     } while (retVal > 0);
  110.  
  111.     closesocket(clientSock);
  112.     cout << "Connection closed" << endl;
  113. }
  114.  
  115. int main(void)
  116. {
  117.     setlocale(LC_ALL, "Russian");
  118.     WORD sockVer;
  119.     WSADATA wsaData;
  120.     int retVal;
  121.  
  122.     sockVer = MAKEWORD(2, 2);
  123.     WSAStartup(sockVer, &wsaData);
  124.  
  125.     SOCKET servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  126.  
  127.     if (servSock == INVALID_SOCKET)
  128.     {
  129.         cerr << "Failed to create socket. Error: " << WSAGetLastError() << endl;
  130.         WSACleanup();
  131.         system("pause");
  132.         return SOCKET_ERROR;
  133.     }
  134.  
  135.     sockaddr_in sin;
  136.     sin.sin_family = AF_INET;
  137.  
  138.     // Ввод номера прослушивающего порта с клавиатуры
  139.     cout << "Enter the listening port number: ";
  140.     int port;
  141.     cin >> port;
  142.     sin.sin_port = htons(port);
  143.  
  144.     // Обработка запросов из любых типов сетей
  145.     sin.sin_addr.s_addr = INADDR_ANY;
  146.  
  147.     retVal = bind(servSock, reinterpret_cast<LPSOCKADDR>(&sin), sizeof(sin));
  148.  
  149.     if (retVal == SOCKET_ERROR)
  150.     {
  151.         cerr << "Failed to bind. Error: " << WSAGetLastError() << endl;
  152.         closesocket(servSock);
  153.         WSACleanup();
  154.         system("pause");
  155.         return SOCKET_ERROR;
  156.     }
  157.  
  158.     // Output the computer's IP address to the screen
  159.     char hostbuffer[256];
  160.     gethostname(hostbuffer, sizeof(hostbuffer));
  161.  
  162.     hostent* host_entry;
  163.     host_entry = gethostbyname(hostbuffer);
  164.  
  165.     char* host_ip = inet_ntoa(*reinterpret_cast<in_addr*>(host_entry->h_addr_list[0]));
  166.     cout << "Computer's IP address: " << host_ip << endl;
  167.  
  168.     printf("Server is running on %s, port %d\n", host_ip, htons(sin.sin_port));
  169.     while (true)
  170.     {
  171.         retVal = listen(servSock, 10);
  172.         if (retVal == SOCKET_ERROR)
  173.         {
  174.             cerr << "Failed to listen to the socket. Error: " << WSAGetLastError() << endl;
  175.             closesocket(servSock);
  176.             WSACleanup();
  177.             system("pause");
  178.             return SOCKET_ERROR;
  179.         }
  180.  
  181.         sockaddr_in from;
  182.         int fromlen = sizeof(from);
  183.         SOCKET clientSock = accept(servSock, reinterpret_cast<struct sockaddr*>(&from), &fromlen);
  184.  
  185.         if (clientSock == INVALID_SOCKET)
  186.         {
  187.             cerr << "Failed to accept the connection. Error: " << WSAGetLastError() << endl;
  188.             closesocket(servSock);
  189.             WSACleanup();
  190.             system("pause");
  191.             return SOCKET_ERROR;
  192.         }
  193.  
  194.         cout << "New connection from " << inet_ntoa(from.sin_addr) << ", port " << htons(from.sin_port) << endl;
  195.  
  196.         handleClient(clientSock, from);
  197.     }
  198.  
  199.     closesocket(servSock);
  200.     WSACleanup();
  201.     return 0;
  202. }
  203. /*void insertServerInfo(char* text, size_t bufferSize, const char* serverIP, int serverPort)
  204. {
  205.     // Create a string stream to manipulate the text
  206.     std::ostringstream oss;
  207.  
  208.     // Append the original text to the stream
  209.     oss << text << " Server IP: " << serverIP << ", Port: " << serverPort;
  210.  
  211.     // Get the resulting string
  212.     std::string result = oss.str();
  213.  
  214.     // Ensure the result fits into the buffer
  215.     if (result.length() < bufferSize)
  216.     {
  217.         // Copy the modified text back to the original buffer
  218.         strncpy_s(text, bufferSize, result.c_str(), _TRUNCATE);
  219.     }
  220.     else
  221.     {
  222.         cerr << "Modified text exceeds the buffer size. Handle this case accordingly." << endl;
  223.     }
  224. }
  225.  
  226. void handleClient(SOCKET clientSock, const sockaddr_in& sin)
  227. {
  228.     int retVal;
  229.  
  230.     do
  231.     {
  232.         char szReq[512];
  233.         retVal = recv(clientSock, szReq, sizeof(szReq) - 1, 0);
  234.  
  235.         if (retVal == SOCKET_ERROR)
  236.         {
  237.             cerr << "Failed to receive data. Error: " << WSAGetLastError() << endl;
  238.             closesocket(clientSock);
  239.             return;
  240.         }
  241.  
  242.         if (retVal == 0)
  243.         {
  244.             cout << "Client disconnected" << endl;
  245.             closesocket(clientSock);
  246.             return;
  247.         }
  248.  
  249.         szReq[retVal] = '\0';
  250.         cout << "Data received: " << szReq << endl;
  251.  
  252.         // Modify the text by inserting server information at the end of each sentence
  253.         insertServerInfo(szReq, sizeof(szReq), inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
  254.  
  255.         // Tokenize the text into sentences
  256.         std::istringstream iss(szReq);
  257.         std::string sentence;
  258.  
  259.         // Display and send the modified text back to the client
  260.         while (std::getline(iss, sentence, '.'))
  261.         {
  262.             cout << "Modified text from server: " << sentence << "  Server IP: " << inet_ntoa(sin.sin_addr) << ", Port: " << ntohs(sin.sin_port) << "." << endl;
  263.  
  264.             // Send the modified sentence back to the client
  265.             retVal = send(clientSock, (sentence + "  Server IP: " + inet_ntoa(sin.sin_addr) + ", Port: " + std::to_string(ntohs(sin.sin_port)) + ".").c_str(), retVal, 0);
  266.  
  267.             if (retVal == SOCKET_ERROR)
  268.             {
  269.                 cerr << "Failed to send data. Error: " << WSAGetLastError() << endl;
  270.                 closesocket(clientSock);
  271.                 return;
  272.             }
  273.         }
  274.  
  275.     } while (retVal > 0);
  276.  
  277.     closesocket(clientSock);
  278.     cout << "Connection closed" << endl;
  279. }
  280.  
  281. int main(void)
  282. {
  283.     setlocale(LC_ALL, "Russian");
  284.     WORD sockVer;
  285.     WSADATA wsaData;
  286.     int retVal;
  287.  
  288.     sockVer = MAKEWORD(2, 2);
  289.     WSAStartup(sockVer, &wsaData);
  290.  
  291.     SOCKET servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  292.  
  293.     if (servSock == INVALID_SOCKET)
  294.     {
  295.         cerr << "Failed to create socket. Error: " << WSAGetLastError() << endl;
  296.         WSACleanup();
  297.         system("pause");
  298.         return SOCKET_ERROR;
  299.     }
  300.  
  301.     sockaddr_in sin;
  302.     sin.sin_family = AF_INET;
  303.  
  304.     // Ввод номера прослушивающего порта с клавиатуры
  305.     cout << "Enter the listening port number: ";
  306.     int port;
  307.     cin >> port;
  308.     sin.sin_port = htons(port);
  309.  
  310.     // Обработка запросов из любых типов сетей
  311.     sin.sin_addr.s_addr = INADDR_ANY;
  312.  
  313.     retVal = bind(servSock, reinterpret_cast<LPSOCKADDR>(&sin), sizeof(sin));
  314.  
  315.     if (retVal == SOCKET_ERROR)
  316.     {
  317.         cerr << "Failed to bind. Error: " << WSAGetLastError() << endl;
  318.         closesocket(servSock);
  319.         WSACleanup();
  320.         system("pause");
  321.         return SOCKET_ERROR;
  322.     }
  323.  
  324.     // Output the computer's IP address to the screen
  325.     char hostbuffer[256];
  326.     gethostname(hostbuffer, sizeof(hostbuffer));
  327.  
  328.     hostent* host_entry;
  329.     host_entry = gethostbyname(hostbuffer);
  330.  
  331.     char* host_ip = inet_ntoa(*reinterpret_cast<in_addr*>(host_entry->h_addr_list[0]));
  332.     cout << "Computer's IP address: " << host_ip << endl;
  333.  
  334.     printf("Server is running on %s, port %d\n", host_ip, htons(sin.sin_port));
  335.     while (true)
  336.     {
  337.         retVal = listen(servSock, 10);
  338.  
  339.         if (retVal == SOCKET_ERROR)
  340.         {
  341.             cerr << "Failed to listen to the socket. Error: " << WSAGetLastError() << endl;
  342.             closesocket(servSock);
  343.             WSACleanup();
  344.             system("pause");
  345.             return SOCKET_ERROR;
  346.         }
  347.  
  348.         sockaddr_in from;
  349.         int fromlen = sizeof(from);
  350.  
  351.         SOCKET clientSock = accept(servSock, reinterpret_cast<struct sockaddr*>(&from), &fromlen);
  352.  
  353.         if (clientSock == INVALID_SOCKET)
  354.         {
  355.             cerr << "Failed to accept the connection. Error: " << WSAGetLastError() << endl;
  356.             closesocket(servSock);
  357.             WSACleanup();
  358.             system("pause");
  359.             return SOCKET_ERROR;
  360.         }
  361.  
  362.         cout << "New connection from " << inet_ntoa(from.sin_addr) << ", port " << htons(from.sin_port) << endl;
  363.  
  364.         handleClient(clientSock, from);
  365.     }
  366.  
  367.     closesocket(servSock);
  368.     WSACleanup();
  369.     return 0;
  370. }*/
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement