forked from CobaltFusion/DebugViewPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Socket.cpp
78 lines (64 loc) · 2.32 KB
/
Socket.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
70
71
72
73
74
75
76
77
78
// (C) Copyright Gert-Jan de Vos and Jan Wilmans 2013.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// Repository at: https://github.com/djeedjay/DebugViewPP/
#include "stdafx.h"
#include "Win32/Win32Lib.h"
#include "Win32/Socket.h"
namespace fusion {
namespace Win32 {
WinsockInitialization::WinsockInitialization(int major, int minor)
{
WSADATA wsaData = { 0 };
int rc = WSAStartup(MAKEWORD(major, minor), &wsaData);
if (rc != 0)
ThrowWin32Error(rc, "WSAStartup");
}
WinsockInitialization::~WinsockInitialization()
{
WSACleanup();
}
void WSAThrowLastError(const std::string& what)
{
Win32::ThrowWin32Error(WSAGetLastError(), what);
}
void SocketDeleter::operator()(pointer p) const
{
if (p != INVALID_SOCKET)
closesocket(p);
}
Socket WSASocket(int af, int type, int protocol)
{
return WSASocket(af, type, protocol, nullptr, 0, 0);
}
Socket WSASocket(int af, int type, int protocol, const WSAPROTOCOL_INFO* pProtocolInfo, GROUP g, DWORD flags)
{
SOCKET s = ::WSASocket(af, type, protocol, const_cast<WSAPROTOCOL_INFO*>(pProtocolInfo), g, flags);
if (s == INVALID_SOCKET)
WSAThrowLastError("WSASocket");
return Socket(s);
}
void bind(Socket& socket, const sockaddr_in& sa)
{
if (::bind(socket.get(), reinterpret_cast<const sockaddr*>(&sa), sizeof(sa)) == SOCKET_ERROR)
WSAThrowLastError("bind");
}
bool WSARecvFrom(Socket& s, const WSABUF buffers[], DWORD bufferCount, DWORD* pNumberOfBytesRecvd, DWORD* pFlags, sockaddr_in& from, int& fromLen, WSAOVERLAPPED* pOverlapped, LPWSAOVERLAPPED_COMPLETION_ROUTINE pCompletionRoutine)
{
if (::WSARecvFrom(s.get(), const_cast<WSABUF*>(buffers), bufferCount, pNumberOfBytesRecvd, pFlags, reinterpret_cast<sockaddr*>(&from), &fromLen, pOverlapped, pCompletionRoutine) != SOCKET_ERROR)
return true;
auto err = WSAGetLastError();
if (err != WSA_IO_PENDING)
ThrowWin32Error(err, "WSARecvFrom");
return false;
}
DWORD WSAGetOverlappedResult(Socket& s, WSAOVERLAPPED& overlapped, bool wait, DWORD& flags)
{
DWORD count;
if (!::WSAGetOverlappedResult(s.get(), &overlapped, &count, wait, &flags))
Win32::WSAThrowLastError("WSAGetOverlappedResult");
return count;
}
} // namespace Win32
} // namespace fusion