-
Notifications
You must be signed in to change notification settings - Fork 0
/
netutil.cpp
69 lines (57 loc) · 1.97 KB
/
netutil.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
//Copyright © 2023 Charles Kerr. All rights reserved.
#include "netutil.hpp"
#include <iostream>
#include <stdexcept>
#if defined (_WIN32)
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#pragma comment(lib,"Ws2_32.lib")
#else
#include <errno.h>
#endif
using namespace std::string_literals;
namespace util {
namespace net {
//=================================================================================
// Intialize the network
auto initialize() ->void{
#if defined(_WIN32)
WSADATA wsa_data ;
auto results = WSAStartup(MAKEWORD(2,2),&wsa_data);
if (results != 0){
results = WSAGetLastError();
auto msg = errormsg(results);
throw std::runtime_error("Error initializing network: "s + msg);
}
if ( LOBYTE(wsa_data.wVersion ) != 2 ||
HIBYTE(wsa_data.wVersion ) != 2 ) {
WSACleanup( );
throw std::runtime_error("Unable to obtain minimum WinSock version of 2.2 "s);
}
#endif
}
//========================================================================
auto shutdown() ->void {
#if defined(_WIN32)
WSACleanup();
#endif
}
//========================================================================
auto errormsg(int error) ->std::string {
auto value = std::string();
#if !defined(_WIN32)
value = std::strerror(error);
#else
LPTSTR buffer = NULL;
error = WSAGetLastError();
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPTSTR>(&buffer), 0, NULL);
if (buffer != NULL) {
value = *buffer;
LocalFree(buffer);
}
#endif
return value;
}
}
}