7#error include tcp_client-windows.h instead
14#include <sys/socket.h>
18#include <netinet/tcp.h>
19#include <netinet/in.h>
57 void connect(
const std::string& host,
int port)
63 memset(&hints, 0,
sizeof(
struct addrinfo));
64 hints.ai_family = AF_INET;
65 hints.ai_socktype = SOCK_STREAM;
66 hints.ai_flags = AI_NUMERICSERV;
67 hints.ai_protocol = 0;
69 auto port_str = std::to_string(port);
70 struct addrinfo* addrinfo_result;
71 auto rv = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &addrinfo_result);
74 throw_spdlog_ex(fmt_lib::format(
"::getaddrinfo failed: {}", gai_strerror(rv)));
79 for (
auto*
rp = addrinfo_result;
rp !=
nullptr;
rp =
rp->ai_next)
81#if defined(SOCK_CLOEXEC)
82 const int flags = SOCK_CLOEXEC;
86 socket_ = ::socket(
rp->ai_family,
rp->ai_socktype | flags,
rp->ai_protocol);
101 ::freeaddrinfo(addrinfo_result);
109 ::setsockopt(
socket_, IPPROTO_TCP, TCP_NODELAY,
reinterpret_cast<char*
>(&enable_flag),
sizeof(enable_flag));
112#if defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
113 ::setsockopt(
socket_, SOL_SOCKET, SO_NOSIGPIPE,
reinterpret_cast<char*
>(&enable_flag),
sizeof(enable_flag));
116#if !defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
117#error "tcp_sink would raise SIGPIPE since neither SO_NOSIGPIPE nor MSG_NOSIGNAL are available"
125 size_t bytes_sent = 0;
126 while (bytes_sent < n_bytes)
128#if defined(MSG_NOSIGNAL)
129 const int send_flags = MSG_NOSIGNAL;
131 const int send_flags = 0;
133 auto write_result =
::send(
socket_,
data + bytes_sent, n_bytes - bytes_sent, send_flags);
134 if (write_result < 0)
140 if (write_result == 0)
144 bytes_sent +=
static_cast<size_t>(write_result);
bool is_connected() const
Definition tcp_client.h:32
int fd() const
Definition tcp_client.h:46
void connect(const std::string &host, int port)
Definition tcp_client.h:57
~tcp_client()
Definition tcp_client.h:51
void send(const char *data, size_t n_bytes)
Definition tcp_client.h:123
void close()
Definition tcp_client.h:37
SOCKET socket_
Definition tcp_client-windows.h:28
SPDLOG_INLINE void throw_spdlog_ex(const std::string &msg, int last_errno)
Definition common-inl.h:75
rp
Definition tag_strings.h:66
annotation details
Definition tag_strings.h:125