split into src and lib and socket changes

* libanthracite files are now all in lib/
* anthracite-bin + anthracite-api-bin files are now all in src/
* socket split into header and source properly
This commit is contained in:
Nicholas Orlowsky 2025-02-04 11:37:46 -05:00
parent fba87f3fbb
commit 71be773d49
Signed by: nickorlow
GPG key ID: 838827D8C4611687
24 changed files with 49 additions and 121 deletions

77
lib/socket/socket.cpp Normal file
View file

@ -0,0 +1,77 @@
#include <arpa/inet.h>
#include <array>
#include <malloc.h>
#include <netinet/in.h>
#include <string>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#include <vector>
#include "./socket.hpp"
namespace anthracite::socket {
anthracite_socket::anthracite_socket(int port, int max_queue)
: server_socket(::socket(AF_INET, SOCK_STREAM, 0))
, client_ip("")
{
struct sockaddr_in address {};
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = INADDR_ANY;
int reuse_opt = 1;
setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &reuse_opt, sizeof(reuse_opt));
bind(server_socket, reinterpret_cast<struct sockaddr*>(&address), sizeof(address));
listen(server_socket, max_queue);
}
void anthracite_socket::wait_for_conn()
{
client_ip = "";
client_socket = accept(server_socket, reinterpret_cast<struct sockaddr*>(&client_addr), &client_addr_len);
std::array<char, INET_ADDRSTRLEN> ip_str { 0 };
inet_ntop(AF_INET, &client_addr.sin_addr, ip_str.data(), INET_ADDRSTRLEN);
client_ip = std::string(ip_str.data());
}
const std::string& anthracite_socket::get_client_ip()
{
return client_ip;
}
void anthracite_socket::close_conn()
{
close(client_socket);
client_socket = -1;
}
void anthracite_socket::send_message(std::string& msg)
{
if (client_socket == -1) {
return;
}
send(client_socket, &msg[0], msg.length(), 0);
}
std::string anthracite_socket::recv_message(int buffer_size)
{
if (client_socket == -1) {
return "";
}
setsockopt(client_socket, SOL_SOCKET, SO_RCVTIMEO, &timeout_tv, sizeof timeout_tv);
std::vector<char> response(buffer_size + 1);
ssize_t result = recv(client_socket, response.data(), buffer_size + 1, 0);
if (result < 1) {
return "";
}
response[buffer_size] = '\0';
return { response.data() };
}
};

34
lib/socket/socket.hpp Normal file
View file

@ -0,0 +1,34 @@
#include <arpa/inet.h>
#include <malloc.h>
#include <netinet/in.h>
#include <string>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
namespace anthracite::socket {
class anthracite_socket {
static const int MAX_QUEUE_LENGTH = 100;
private:
int server_socket;
int client_socket {};
std::string client_ip;
struct sockaddr_in client_addr {};
socklen_t client_addr_len {};
static constexpr struct timeval timeout_tv {
.tv_sec = 5, .tv_usec = 0
};
public:
anthracite_socket(int port, int max_queue = MAX_QUEUE_LENGTH);
void wait_for_conn();
const std::string& get_client_ip();
void close_conn();
void send_message(std::string& msg);
std::string recv_message(int buffer_size);
};
};