From 27f3043a55e97c13eb586cf71a3d50cf48f67aca Mon Sep 17 00:00:00 2001 From: crupest Date: Sun, 6 Jun 2021 22:05:28 +0800 Subject: ... --- computer-network-experiment/Common.cpp | 48 ++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 computer-network-experiment/Common.cpp (limited to 'computer-network-experiment/Common.cpp') diff --git a/computer-network-experiment/Common.cpp b/computer-network-experiment/Common.cpp new file mode 100644 index 0000000..02ac550 --- /dev/null +++ b/computer-network-experiment/Common.cpp @@ -0,0 +1,48 @@ +#include "Common.h" + +#include "Output.h" + +#ifdef WIN32 +#include +#include +#pragma comment(lib, "Ws2_32.lib") +#endif + +[[noreturn]] void PrintErrorMessageAndExit(StringView message, + bool print_last_error) { + + SendOutput(CRUT("{}\n"), message); + + if (print_last_error) { +#ifdef WIN32 + auto error_code = WSAGetLastError(); + SendOutput(OutputType::Error, CRUT("Error code is {}.\n"), error_code); + wchar_t buffer[500]; + if (!FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | + FORMAT_MESSAGE_ARGUMENT_ARRAY | + FORMAT_MESSAGE_IGNORE_INSERTS, + nullptr, error_code, 0, buffer, 500, nullptr)) { + SendOutput(OutputType::Error, CRUT("Failed to format error message.\n")); + } else { + SendOutput(OutputType::Error, CRUT("{}\n"), buffer); + } +#else +#endif + } + +#ifdef WIN32 + WSACleanup(); +#endif + + std::exit(1); +} + +#ifdef WIN32 +void InitWSA() { + WSADATA wsa_data; + + if (WSAStartup(MAKEWORD(2, 2), &wsa_data)) { // initialize wsa + PrintErrorMessageAndExit(CRUT("Failed to initialize wsa.")); + } +} +#endif -- cgit v1.2.3