2026-01-07 22:16:33 +00:00

85 lines
2.2 KiB
C++

#include "net.hpp"
#include <sys/types.h>
Socket::Socket() {
sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
throw runtime_error("Failed to create socket");
}
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
}
Socket::~Socket() {
close(sock);
}
void Socket::connect_server(const char *ip, uint16_t port) {
server_addr.sin_port = htons(port);
if (inet_pton(AF_INET, ip, &server_addr.sin_addr) <= 0) {
throw runtime_error("Invalid IP address");
}
}
// Connect to existing UNIX domain socket (e.g., /tmp/socket_path)
void Socket::connect_unix(const char *ip, uint16_t port) {
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock < 0) {
throw std::runtime_error("Failed to create UNIX socket");
}
this->server_addr_unix.sun_family = AF_UNIX;
strncpy(this->server_addr_unix.sun_path, ip, sizeof(this->server_addr_unix.sun_path) - 1);
printf("Connecting to UNIX socket at %s\n", ip);
if (connect(sock, (struct sockaddr *)&server_addr_unix, sizeof(server_addr_unix)) < 0) {
throw std::runtime_error("Failed to connect to UNIX socket");
}
}
void Socket::send_server() {
ssize_t sent_bytes = sendto(sock, &packet_data, sizeof(packet_data), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (sent_bytes < 0) {
throw runtime_error("Failed to send data");
}
}
void Socket::send_unix() {
ssize_t sent_bytes = send(sock, &packet_data, sizeof(packet_data), 0);
if (sent_bytes < 0) {
throw runtime_error("Failed to send data to UNIX socket");
}
}
void Socket::send_server(const api_packet &data) {
ssize_t sent_bytes = sendto(sock, &data, sizeof(data), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (sent_bytes < 0) {
throw runtime_error("Failed to send data");
}
}
void Socket::send_unix(const api_packet &data) {
ssize_t sent_bytes = send(sock, &data, sizeof(data), 0);
if (sent_bytes < 0) {
throw runtime_error("Failed to send data to UNIX socket");
}
}
void Socket::set_packet(const api_packet &data) {
packet_data = data;
}
api_packet Socket::create_packet(uint8_t tracker_id) {
api_packet pkt;
memset(&pkt, 0, sizeof(pkt));
pkt.message_type = 65; // Handshake message type
pkt.tracker_id = tracker_id;
return pkt;
}
api_packet Socket::get_packet() {
return packet_data;
}