tycho / crisscross

A C++ library with various uses.

This URL has Read+Write access

crisscross / source / core_network.cpp
100644 83 lines (68 sloc) 1.573 kb
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
79
80
81
82
83
/*
* CrissCross
* A multi-purpose cross-platform library.
*
* A product of Uplink Laboratories.
*
* (c) 2006-2009 Steven Noonan.
* Licensed under the New BSD License.
*
*/
 
#include <crisscross/universal_include.h>
#include <crisscross/core_network.h>
 
#if !defined (TARGET_OS_WINDOWS)
#include <sys/socket.h>
#include <signal.h>
#endif
 
namespace
{
int s_initialised = 0;
}
 
CrissCross::Errors CrissCross::Network::__initialise_network()
{
if (!s_initialised) {
#ifdef TARGET_OS_WINDOWS
/* Start up the windows networking */
WORD version_wanted = MAKEWORD(2, 2);
WSADATA wsaData;
 
if (WSAStartup(version_wanted, &wsaData) != 0)
return CC_ERR_INTERNAL;
 
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
return CC_ERR_INTERNAL;
 
#else
/* SIGPIPE is generated when a remote socket is closed */
void (*handler)(int);
handler = signal(SIGPIPE, SIG_IGN);
if (handler != SIG_DFL) {
signal(SIGPIPE, handler);
}
 
#endif
}
 
++s_initialised;
return CC_ERR_NONE;
}
 
CrissCross::Errors CrissCross::Network::__cleanup_network()
{
if (s_initialised == 0) {
return CC_ERR_NONE;
}
 
if (--s_initialised == 0) {
#ifdef TARGET_OS_WINDOWS
/* Clean up windows networking */
if (WSACleanup() == SOCKET_ERROR) {
if (WSAGetLastError() == WSAEINPROGRESS) {
WSACancelBlockingCall();
WSACleanup();
}
}
 
#else
/* Restore the SIGPIPE handler */
void (*handler)(int);
handler = signal(SIGPIPE, SIG_DFL);
if (handler != SIG_IGN) {
signal(SIGPIPE, handler);
}
 
#endif
}
 
return CC_ERR_NONE;
}