Skip to content

Commit 5859e06

Browse files
authored
Address gethostname failure due to missing WinSock initialization (#1363)
1 parent 995f64a commit 5859e06

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/bsoncxx/test/catch.cpp

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,41 @@
1818

1919
#include <bsoncxx/v1/config/export.hpp>
2020

21+
#include <cstdlib>
22+
#include <iostream>
2123
#include <system_error>
2224

25+
#include <bsoncxx/private/bson.hh> // <winsock.h> via <bson/bson-compat.h>
26+
2327
#include <catch2/catch_session.hpp>
2428

29+
// Ensure the Winsock DLL is initialized prior to calling `gethostname` in `bsoncxx::oid::oid()`:
30+
// - bson_oid_init -> bson_context_get_default -> ... -> _bson_context_init_random -> gethostname.
31+
struct WSAGuard {
32+
~WSAGuard() {
33+
#if defined(_WIN32)
34+
(void)WSACleanup();
35+
#endif
36+
}
37+
38+
WSAGuard(WSAGuard&&) = delete;
39+
WSAGuard& operator=(WSAGuard&) = delete;
40+
WSAGuard(WSAGuard const&) = delete;
41+
WSAGuard& operator=(WSAGuard const&) = delete;
42+
43+
WSAGuard() {
44+
#if defined(_WIN32)
45+
WSADATA wsaData;
46+
if (WSAStartup((MAKEWORD(2, 2)), &wsaData) != 0) {
47+
std::cerr << "WSAStartup failed: " << WSAGetLastError() << std::endl;
48+
std::abort();
49+
}
50+
#endif
51+
}
52+
};
53+
2554
int BSONCXX_ABI_CDECL main(int argc, char* argv[]) {
55+
WSAGuard wsa_guard;
2656
return Catch::Session().run(argc, argv);
2757
}
2858

0 commit comments

Comments
 (0)