23 #include <arpa/inet.h> 25 #include <netinet/tcp.h> 47 setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, &flag,
sizeof(
int));
48 setsockopt(socket_fd, IPPROTO_TCP, TCP_QUICKACK, &flag,
sizeof(
int));
52 setsockopt(socket_fd, SOL_SOCKET, SO_RCVTIMEO,
recv_timeout_.get(),
sizeof(timeval));
61 URCL_LOG_DEBUG(
"Setting up connection: %s:%d", host.c_str(), port);
66 const char* host_name = host.empty() ?
nullptr : host.c_str();
67 std::string service = std::to_string(port);
68 struct addrinfo hints, *result;
69 std::memset(&hints, 0,
sizeof(hints));
71 hints.ai_family = AF_UNSPEC;
72 hints.ai_socktype = SOCK_STREAM;
73 hints.ai_flags = AI_PASSIVE;
75 if (getaddrinfo(host_name, service.c_str(), &hints, &result) != 0)
77 URCL_LOG_ERROR(
"Failed to get address for %s:%d", host.c_str(), port);
81 bool connected =
false;
83 for (
struct addrinfo* p = result; p !=
nullptr; p = p->ai_next)
85 socket_fd_ = ::socket(p->ai_family, p->ai_socktype, p->ai_protocol);
99 URCL_LOG_ERROR(
"Connection setup failed for %s:%d", host.c_str(), port);
105 URCL_LOG_DEBUG(
"Connection established for %s:%d", host.c_str(), port);
123 socklen_t len =
sizeof(name);
124 int res = ::getsockname(
socket_fd_, (sockaddr*)&name, &len);
129 return std::string();
133 inet_ntop(AF_INET, &name.sin_addr, buf,
sizeof(buf));
134 return std::string(buf);
143 return read((uint8_t*)character, 1, read_chars);
153 ssize_t res = ::recv(
socket_fd_, buf, buf_len, 0);
163 read =
static_cast<size_t>(res);
177 size_t remaining = buf_len;
180 while (written < buf_len)
182 ssize_t sent = ::send(
socket_fd_, buf + written, remaining, 0);
#define URCL_LOG_ERROR(...)
bool write(const uint8_t *buf, const size_t buf_len, size_t &written)
Writes to the socket.
std::atomic< SocketState > state_
Connection to socket got closed.
std::atomic< int > socket_fd_
SocketState
State the socket can be in.
std::unique_ptr< timeval > recv_timeout_
Socket is initialized or setup failed.
Socket is disconnected and cannot be used.
bool read(char *character)
Reads one byte from the socket.
#define URCL_LOG_DEBUG(...)
bool setup(std::string &host, int port)
void close()
Closes the connection to the socket.
std::string getIP() const
Determines the local IP address of the currently configured socket.
Socket is connected and ready to use.
virtual void setOptions(int socket_fd)
virtual bool open(int socket_fd, struct sockaddr *address, size_t address_len)
void setReceiveTimeout(const timeval &timeout)
Setup Receive timeout used for this socket.
TCPSocket()
Creates a TCPSocket object.