initial implementation

This commit is contained in:
PoliEcho 2024-12-07 15:04:50 +01:00
parent 50c6cc3206
commit b3ec1a7891

104
main.cpp Normal file
View File

@ -0,0 +1,104 @@
#include <arpa/inet.h>
#include <array>
#include <codecvt>
#include <csignal>
#include <cstdio>
#include <fcntl.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <netdb.h>
#include <netinet/in.h>
#include <stdexcept>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <unistd.h>
#define PORT 54321
std::string exec(std::string cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, void (*)(FILE *)> pipe(popen(cmd.c_str(), "r"),
[](FILE *f) -> void {
// wrapper to ignore the return
// value from pclose() is
// needed with newer versions
// of gnu g++
std::ignore = pclose(f);
});
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe.get()) !=
nullptr) {
result += buffer.data();
}
return result;
}
int serverSocket;
void safe_exit(int code) {
std::clog << "Exiting\n";
close(serverSocket);
exit(code);
}
int main(int argc, char *argv[]) {
// signal handlers
signal(SIGTERM, safe_exit);
signal(SIGINT, safe_exit);
signal(SIGQUIT, safe_exit);
signal(SIGHUP, safe_exit);
// error signal handlers
signal(SIGSEGV, safe_exit);
// creating socket
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
// specifying the address
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(PORT);
serverAddress.sin_addr.s_addr = INADDR_ANY;
// binding socket.
while (bind(serverSocket, (struct sockaddr *)&serverAddress,
sizeof(serverAddress)) != 0) {
std::cerr << "error binding socket retring\n";
sleep(2);
}
// listening to the assigned socket
listen(serverSocket, 5);
// accepting connection request
int clientSocket = accept(serverSocket, nullptr, nullptr);
// recieving data
char buffer[1024] = {0};
{
int RecvRetVal = recv(clientSocket, buffer, sizeof(buffer), 0);
if (RecvRetVal > sizeof(buffer) || RecvRetVal < 0) {
std::cerr << "recv() returned an error code\n";
return RecvRetVal;
}
}
std::cout << "Message from client: " << buffer << std::endl;
// closing the socket.
close(serverSocket);
return 0;
}