Skip to content

Commit

Permalink
fix(cpp-client): WinSock calls need to be prefaced by WSAStartup (#5986)
Browse files Browse the repository at this point in the history
  • Loading branch information
kosak committed Aug 26, 2024
1 parent 5fc0504 commit 28ac180
Showing 1 changed file with 33 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
* Copyright (c) 2016-2024 Deephaven Data Labs and Patent Pending
*/
#include <climits>
#include <mutex>
#include <optional>
#include <string>
#include "deephaven/dhcore/utility/utility.h"
Expand Down Expand Up @@ -31,6 +32,36 @@ std::string GetTidAsString() {
#endif
}

#if defined(_WIN32)
namespace {
// We need to call WSAStartup() before using other Winsock calls.
// We only do this once during the lifetime of the program; and we
// never bother to call WSACleanup().
void EnsureWsaStartup() {
static std::mutex mutex;
static bool startupSucceeded = false;

std::unique_lock guard(mutex);
if (startupSucceeded) {
return;
}

int32_t versionRequested = 0x202;
WSADATA wsaData;
auto err = WSAStartup(versionRequested, &wsaData);
if (err != 0) {
auto message = fmt::format("WSAStartup failed with error: {}", err);
throw std::runtime_error(DEEPHAVEN_LOCATION_STR(message));
}
if (wsaData.wVersion != versionRequested) {
auto message = fmt::format("Got an unexpected version {:x} of winsock.dll", wsaData.wVersion);
throw std::runtime_error(DEEPHAVEN_LOCATION_STR(message));
}
startupSucceeded = true;
}
} // namespace
#endif

std::string GetHostname() {
#if defined(__unix__)
char hostname[HOST_NAME_MAX];
Expand Down Expand Up @@ -59,6 +90,7 @@ std::string GetHostname() {
freeaddrinfo(info);
return result;
#elif defined(_WIN32)
EnsureWsaStartup();
char hostname[256];
const int r = gethostname(hostname, sizeof(hostname));
if (r != 0) {
Expand Down Expand Up @@ -117,6 +149,6 @@ void SetStdinEcho(const bool enable) {
#else
#error "Unsupported configuration"
#endif
}
}

} // namespace deephaven::dhcore::utility

0 comments on commit 28ac180

Please sign in to comment.