aboutsummaryrefslogtreecommitdiff
path: root/works/life/computer-network-experiment/Common.cpp
diff options
context:
space:
mode:
authorcrupest <crupest@outlook.com>2021-06-06 22:05:28 +0800
committercrupest <crupest@outlook.com>2021-06-06 22:05:28 +0800
commitf0309ee1e5cd268091f59f3aa377beca77d76c5c (patch)
tree14b86eaf2b9181d9a171ee8c9d11173beeebec52 /works/life/computer-network-experiment/Common.cpp
parentff92a987ad05e40a1315306b31bbc4a219d2ee1d (diff)
downloadcrupest-f0309ee1e5cd268091f59f3aa377beca77d76c5c.tar.gz
crupest-f0309ee1e5cd268091f59f3aa377beca77d76c5c.tar.bz2
crupest-f0309ee1e5cd268091f59f3aa377beca77d76c5c.zip
import(life): ...
Diffstat (limited to 'works/life/computer-network-experiment/Common.cpp')
-rw-r--r--works/life/computer-network-experiment/Common.cpp48
1 files changed, 48 insertions, 0 deletions
diff --git a/works/life/computer-network-experiment/Common.cpp b/works/life/computer-network-experiment/Common.cpp
new file mode 100644
index 0000000..02ac550
--- /dev/null
+++ b/works/life/computer-network-experiment/Common.cpp
@@ -0,0 +1,48 @@
+#include "Common.h"
+
+#include "Output.h"
+
+#ifdef WIN32
+#include <Windows.h>
+#include <winsock.h>
+#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