1 // Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
2 // Distributed under the MIT License (http://opensource.org/licenses/MIT)
6 #define WIN32_LEAN_AND_MEAN
8 #include <spdlog/common.h>
9 #include <spdlog/details/os.h>
18 #pragma comment(lib, "Ws2_32.lib")
19 #pragma comment(lib, "Mswsock.lib")
20 #pragma comment(lib, "AdvApi32.lib")
26 SOCKET socket_ = INVALID_SOCKET;
28 static void init_winsock_()
31 auto rv = WSAStartup(MAKEWORD(2, 2), &wsaData);
34 throw_winsock_error_("WSAStartup failed", ::WSAGetLastError());
38 static void throw_winsock_error_(const std::string &msg, int last_error)
41 ::FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error,
42 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, (sizeof(buf) / sizeof(char)), NULL);
44 throw_spdlog_ex(fmt_lib::format("tcp_sink - {}: {}", msg, buf));
59 bool is_connected() const
61 return socket_ != INVALID_SOCKET;
66 ::closesocket(socket_);
67 socket_ = INVALID_SOCKET;
75 // try to connect or throw on failure
76 void connect(const std::string &host, int port)
84 ZeroMemory(&hints, sizeof(hints));
86 hints.ai_family = AF_INET; // IPv4
87 hints.ai_socktype = SOCK_STREAM; // TCP
88 hints.ai_flags = AI_NUMERICSERV; // port passed as as numeric value
89 hints.ai_protocol = 0;
91 auto port_str = std::to_string(port);
92 struct addrinfo *addrinfo_result;
93 auto rv = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &addrinfo_result);
97 last_error = ::WSAGetLastError();
99 throw_winsock_error_("getaddrinfo failed", last_error);
102 // Try each address until we successfully connect(2).
104 for (auto *rp = addrinfo_result; rp != nullptr; rp = rp->ai_next)
106 socket_ = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
107 if (socket_ == INVALID_SOCKET)
109 last_error = ::WSAGetLastError();
113 if (::connect(socket_, rp->ai_addr, (int)rp->ai_addrlen) == 0)
119 last_error = ::WSAGetLastError();
123 ::freeaddrinfo(addrinfo_result);
124 if (socket_ == INVALID_SOCKET)
127 throw_winsock_error_("connect failed", last_error);
132 ::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&enable_flag), sizeof(enable_flag));
135 // Send exactly n_bytes of the given data.
136 // On error close the connection and throw.
137 void send(const char *data, size_t n_bytes)
139 size_t bytes_sent = 0;
140 while (bytes_sent < n_bytes)
142 const int send_flags = 0;
143 auto write_result = ::send(socket_, data + bytes_sent, (int)(n_bytes - bytes_sent), send_flags);
144 if (write_result == SOCKET_ERROR)
146 int last_error = ::WSAGetLastError();
148 throw_winsock_error_("send failed", last_error);
151 if (write_result == 0) // (probably should not happen but in any case..)
155 bytes_sent += static_cast<size_t>(write_result);
159 } // namespace details
160 } // namespace spdlog