working commit
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
extern "C" {
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
}
|
||||
|
||||
#include <expected>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <span>
|
||||
#include <iostream>
|
||||
|
||||
#include <cstring>
|
||||
#include <expected>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
|
||||
#include <tcpclient.hpp>
|
||||
|
||||
TCPClient::TCPClient() {
|
||||
sock = 0;
|
||||
family = 0;
|
||||
}
|
||||
|
||||
std::expected<void, std::string> TCPClient::Connect(const std::string naddress, const int port) {
|
||||
|
||||
struct sockaddr_in sa;
|
||||
if (inet_pton(AF_INET, naddress.c_str(), &(sa.sin_addr)) == 1) {
|
||||
family = AF_INET;
|
||||
} else if (inet_pton(AF_INET6, naddress.c_str(), &(sa.sin_addr)) == 1) {
|
||||
family = AF_INET6;
|
||||
} else {
|
||||
int errnocopy = errno;
|
||||
std::string error = std::strerror(errnocopy);
|
||||
return std::unexpected("Incorrect address " + naddress);
|
||||
}
|
||||
|
||||
sock = socket(family, SOCK_STREAM, 0);
|
||||
if (sock < 0) {
|
||||
return std::unexpected("Error opening socket");
|
||||
}
|
||||
struct sockaddr_in serv_addr;
|
||||
memset(&serv_addr, 0, sizeof(serv_addr));
|
||||
|
||||
serv_addr.sin_family = AF_INET;
|
||||
serv_addr.sin_port = htons(port);
|
||||
const char* addr = naddress.data();
|
||||
if (inet_pton(AF_INET, addr, &serv_addr.sin_addr) <= 0) {
|
||||
return std::unexpected("Invalid server IP address");
|
||||
}
|
||||
|
||||
struct timeval timeout;
|
||||
timeout.tv_sec = 5;
|
||||
timeout.tv_usec = 0;
|
||||
|
||||
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof timeout) < 0) {
|
||||
return std::unexpected("Set timeout error");
|
||||
}
|
||||
if (setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof timeout) < 0) {
|
||||
return std::unexpected("Set timeout error");
|
||||
}
|
||||
if (connect(sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
|
||||
return std::unexpected("Connecting error");
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
std::expected<int, std::string> TCPClient::Write(std::string payload) {
|
||||
int n = 0;
|
||||
if ((n = write(sock, payload.data(), payload.size())) < 0) {
|
||||
return std::unexpected("Write error");
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
std::expected<int, std::string> TCPClient::Read(std::string& res, int size) {
|
||||
char buffer[size + 1];
|
||||
memset(&buffer, 0, size + 1);
|
||||
int rsize = 0;
|
||||
if ((rsize = read(sock, &buffer, size)) < 0) {
|
||||
return std::unexpected("Read error");
|
||||
}
|
||||
res.append(buffer, rsize);
|
||||
return rsize;
|
||||
}
|
||||
|
||||
TCPClient::~TCPClient() {
|
||||
close(sock);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user