-
Notifications
You must be signed in to change notification settings - Fork 13
/
Sockets.cpp
297 lines (243 loc) · 6.94 KB
/
Sockets.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/*
Copyright (c) 2011, Chris Pearce
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Chris Pearce nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE ORGANISATION OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <iostream>
#include "Sockets.h"
#include "Utils.h"
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
class Win32Socket : public Socket {
public:
virtual ~Win32Socket();
Socket* Accept();
Win32Socket(SOCKET aSocket);
void Close();
int Send(const char* aBuf, int aSize);
int Receive(char* aBuf, int aSize);
static WSADATA sWsaData;
};
WSADATA Win32Socket::sWsaData = {0};
Win32Socket::Win32Socket(SOCKET aSocket)
: Socket((int)aSocket)
{ }
Win32Socket::~Win32Socket()
{
Close();
}
Socket* Socket::Open(int aPort) {
// Init a server port.
struct addrinfo *addr = NULL, *ptr = NULL, hints;
ZeroMemory(&hints, sizeof (hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;
// Resolve the local address and port to be used by the server
string port = ToString(aPort);
int res = getaddrinfo(NULL, port.c_str(), &hints, &addr);
if (res != 0) {
cerr << "getaddrinfo failed: " << res << std::endl;
return 0;
}
SOCKET serverSocket = INVALID_SOCKET;
// Create a SOCKET for the server to listen for client connections
serverSocket = socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (serverSocket == INVALID_SOCKET) {
cerr << "Error at socket(): " << WSAGetLastError() << std::endl;
freeaddrinfo(addr);
return 0;
}
// Setup the TCP listening socket
res = bind( serverSocket, addr->ai_addr, (int)addr->ai_addrlen);
if (res == SOCKET_ERROR) {
cerr << "bind failed: " << WSAGetLastError() << std::endl;
freeaddrinfo(addr);
closesocket(serverSocket);
return 0;
}
// Address info is no longer needed, we've bound the socket.
freeaddrinfo(addr);
if ( listen( serverSocket, SOMAXCONN ) == SOCKET_ERROR ) {
cerr << "Listen failed with error: " << WSAGetLastError() << std::endl;
closesocket(serverSocket);
return 0;
}
return new Win32Socket(serverSocket);
}
Socket* Win32Socket::Accept() {
SOCKET client = accept(mSocket, NULL, NULL);
if (client == INVALID_SOCKET) {
cerr << "accept failed: " << WSAGetLastError() << std::endl;
closesocket(mSocket);
return 0;
}
return new Win32Socket(client);
}
void Win32Socket::Close() {
if (mSocket != INVALID_SOCKET) {
closesocket(mSocket);
mSocket = (int)INVALID_SOCKET;
}
}
int Win32Socket::Receive(char* aBuf, int aSize) {
memset(aBuf, 0, aSize);
int r = recv(mSocket, aBuf, aSize, 0);
if (r < 0) {
cerr << "recv failed: " << WSAGetLastError() << std::endl;
}
return r;
}
int Win32Socket::Send(const char* aBuf, int aSize) {
return send(mSocket, aBuf, aSize, 0);
}
int Socket::Init() {
// Initialize Winsock
int err = WSAStartup(MAKEWORD(2,2), &Win32Socket::sWsaData);
if (err) {
cerr << "WSAStartup failed: " << err << std::endl;
return 1;
}
return 0;
}
int Socket::Shutdown() {
WSACleanup();
return 0;
}
#else
#include <unistd.h>
#include <netinet/in.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#define SOCKET_ERROR -1
class UnixSocket : public Socket {
public:
virtual ~UnixSocket();
Socket* Accept();
UnixSocket(int aSocket);
void Close();
int Send(const char* aBuf, int aSize);
int Receive(char* aBuf, int aSize);
};
Socket* Socket::Open(int aPort) {
int sockfd;
struct sockaddr_in serv_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
return 0;
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(aPort);
if (bind(sockfd,
(struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
{
perror("ERROR on binding");
return 0;
}
listen(sockfd,5);
return new UnixSocket(sockfd);
}
UnixSocket::UnixSocket(int aSocket)
: Socket(aSocket)
{
}
UnixSocket::~UnixSocket() {
Close();
}
Socket* UnixSocket::Accept() {
socklen_t clilen;
struct sockaddr_in cli_addr;
clilen = sizeof(cli_addr);
if (!WaitForRead(500)) {
return 0;
}
int client = accept(mSocket,
(struct sockaddr *) &cli_addr,
&clilen);
if (client < 0) {
perror("ERROR on accept");
close(mSocket);
return 0;
}
return new UnixSocket(client);
}
void UnixSocket::Close() {
if (mSocket != 0) {
close(mSocket);
mSocket = 0;
}
}
int UnixSocket::Receive(char* aBuf, int aSize) {
memset(aBuf, 0, aSize);
int r = read(mSocket, aBuf, aSize);
if (r < 0) {
fprintf(stderr, "Receive failed\n");
}
return r;
}
int UnixSocket::Send(const char* aBuf, int aSize) {
return write(mSocket, aBuf, aSize);
}
int Socket::Init() {
return 0;
}
int Socket::Shutdown() {
return 0;
}
#endif
bool Socket::WaitForRead(unsigned timeout) {
fd_set socks;
FD_ZERO(&socks);
FD_SET((unsigned)mSocket, &socks);
struct timeval to;
to.tv_sec = 0;
to.tv_usec = timeout;
return select(mSocket + 1, &socks, 0, 0, &to) > 0;
}
string Socket::GetIP() const {
char buf[1024];
if (gethostname(buf, sizeof(buf)) == SOCKET_ERROR) {
return "Unknown";
}
struct hostent *host = gethostbyname(buf);
if(host == NULL) {
return "Unknown";
}
char* localIP;
localIP = inet_ntoa(*(struct in_addr *)*host->h_addr_list);
return string(localIP);
}