21 #include <arpa/inet.h> 23 #include <netinet/tcp.h> 41 setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, &flag,
sizeof(
int));
42 setsockopt(socket_fd, IPPROTO_TCP, TCP_QUICKACK, &flag,
sizeof(
int));
50 LOG_INFO(
"Setting up connection: %s:%d", host.c_str(), port);
55 const char *host_name = host.empty() ?
nullptr : host.c_str();
56 std::string service = std::to_string(port);
57 struct addrinfo hints, *result;
58 std::memset(&hints, 0,
sizeof(hints));
60 hints.ai_family = AF_UNSPEC;
61 hints.ai_socktype = SOCK_STREAM;
62 hints.ai_flags = AI_PASSIVE;
64 if (getaddrinfo(host_name, service.c_str(), &hints, &result) != 0)
66 LOG_ERROR(
"Failed to get address for %s:%d", host.c_str(), port);
70 bool connected =
false;
72 for (
struct addrinfo *p = result; p !=
nullptr; p = p->ai_next)
74 socket_fd_ = ::socket(p->ai_family, p->ai_socktype, p->ai_protocol);
88 LOG_ERROR(
"Connection setup failed for %s:%d", host.c_str(), port);
94 LOG_INFO(
"Connection established for %s:%d", host.c_str(), port);
120 socklen_t len =
sizeof(name);
121 int res = ::getsockname(
socket_fd_, (sockaddr *)&name, &len);
126 return std::string();
130 inet_ntop(AF_INET, &name.sin_addr, buf,
sizeof(buf));
131 return std::string(buf);
140 return read((uint8_t *)character, 1, read_chars);
150 ssize_t res = ::recv(
socket_fd_, buf, buf_len, 0);
160 read =
static_cast<size_t>(res);
171 size_t remaining = buf_len;
174 while (written < buf_len)
176 ssize_t sent = ::send(
socket_fd_, buf + written, remaining, 0);
bool read(char *character)
virtual bool open(int socket_fd, struct sockaddr *address, size_t address_len)
std::atomic< int > socket_fd_
virtual void setOptions(int socket_fd)
bool setSocketFD(int socket_fd)
#define LOG_INFO(format,...)
std::atomic< SocketState > state_
bool write(const uint8_t *buf, size_t buf_len, size_t &written)
bool setup(std::string &host, int port)
#define LOG_ERROR(format,...)