-
Notifications
You must be signed in to change notification settings - Fork 0
/
socket.cpp
374 lines (297 loc) · 7.78 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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
#include "socket.h"
#include <stdio.h>
#include <string.h>
#if defined(_WIN32)
#pragma comment( lib, "wsock32.lib" )
#pragma comment( lib, "Ws2_32.lib" )
#else
#include <errno.h>
#endif
#if defined(_WIN32)
typedef int socklen_t;
#endif
#if defined(_WIN32)
#define BNS_SOCKET_ERROR() printf("Socket error: %d\n", WSAGetLastError())
#else
#define BNS_SOCKET_ERROR() printf("Socket error: %s\n", strerror(errno))
#endif
IPV4Addr::IPV4Addr(int _addr, short _port){
addr = _addr;
port = _port;
}
IPV4Addr::IPV4Addr(unsigned char a, unsigned char b, unsigned char c, unsigned char d, short _port){
addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
port = htons(_port);
}
IPV4Addr::IPV4Addr(const char* hostName, int _port){
#if defined(_WIN32)
struct addrinfo hints = {};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
struct addrinfo* result;
int error = getaddrinfo(hostName, NULL, &hints, &result);
if (result != nullptr) {
addr = ((sockaddr_in*)(result->ai_addr))->sin_addr.s_addr;
port = htons(_port);
freeaddrinfo(result);
}
else {
printf("\nError resolving host: '%s'\n", hostName);
}
#else
#endif
}
void IPV4Addr::WriteToString(char* buffer, int bufferSize){
int hostAddr = ntohl(addr);
short hostPort = ntohs(port);
snprintf(buffer, bufferSize, "%d.%d.%d.%d:%d", (hostAddr >> 24), (hostAddr >> 16) & 0xFF, (hostAddr >> 8) & 0xFF, hostAddr & 0xFF, hostPort);
}
sockaddr_in IPV4Addr::ToSockAddr(){
sockaddr_in ip = {};
ip.sin_addr.s_addr = addr;
ip.sin_port = port;
ip.sin_family = AF_INET;
return ip;
}
bool Socket::Create(SocketProtocol _protocol, SocketBlockingType _blockingType){
protocol = _protocol;
blockingType = _blockingType;
// TODO: socket int type??
if (protocol == SP_UDP){
handle = (int)socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
}
else if (protocol == SP_TCP){
handle = (int)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
}
else{
//uuuuhhhh...
}
if (handle <= 0){
}
#if defined(_WIN32)
if (_blockingType == SBT_NonBlocking){
u_long nonBlocking = 1;
if (ioctlsocket( handle, FIONBIO, &nonBlocking ) != 0){
printf( "failed to set non-blocking\n" );
return false;
}
}
#else
if (_blockingType == SBT_NonBlocking){
int nonBlocking = 1;
if (fcntl( handle, F_SETFL, O_NONBLOCK, nonBlocking) == -1){
printf( "failed to set non-blocking\n" );
return false;
}
}
#endif
return true;
}
bool Socket::Bind(int _port /*= 0*/){
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons((unsigned short)_port);
source.addr = htonl((127 << 24) | 1);
int retVal = ::bind(handle, (const sockaddr*) &address, sizeof(sockaddr_in));
if (retVal < 0 ){
printf( "failed to bind socket\n" );
return false;
}
if (_port == 0) {
sockaddr boundAddr;
socklen_t boundLen = sizeof(sockaddr);
int val = getsockname(handle, &boundAddr, &boundLen);
if (val != 0) {
#if defined(_WIN32)
printf("\nWarning: could not determine port of socket (error %d).\n", WSAGetLastError());
#else
printf("\nWarning: could not determine port of socket.\n");
#endif
source.port = 0;
}
else {
source.port = ((sockaddr_in*)(&boundAddr))->sin_port;
}
}
else {
source.port = htons(_port);
}
return true;
}
bool Socket::Connect(IPV4Addr addr){
destination = addr;
source = IPV4Addr(127, 0, 0, 1, source.port);
sockaddr_in dstAddr = destination.ToSockAddr();
int ret = connect(handle, (sockaddr*)(&dstAddr), sizeof(dstAddr));
if (ret != 0) {
#if defined(_WIN32)
int err = WSAGetLastError();
printf("connect failed (err: %d)\n", err);
#else
printf("connect failed\n");
#endif
return false;
}
else {
return true;
}
}
bool Socket::SetBlocking(SocketBlockingType bt) {
#if defined(_WIN32)
u_long iMode = (bt == SBT_NonBlocking ? 1 : 0);
int rv = ioctlsocket(handle, FIONBIO, &iMode);
return rv == 0;
#else
int nonBlocking = (bt == SBT_NonBlocking ? 1 : 0);
if (fcntl( handle, F_SETFL, O_NONBLOCK, nonBlocking) == -1){
printf( "failed to set non-blocking\n" );
return false;
}
else{
return true;
}
#endif
}
bool Socket::SendData(const void* buffer, int buffLength, int* bytesSent){
char srcAddr[256] = {};
char dstAddr[256] = {};
source.WriteToString(srcAddr, sizeof(srcAddr));
destination.WriteToString(dstAddr, sizeof(dstAddr));
printf("Sending %d bytes from '%s' to '%s'\n", buffLength, srcAddr, dstAddr);
sockaddr_in address = destination.ToSockAddr();
int sentBytes = sendto(handle, (const char*)buffer, buffLength, 0, (sockaddr*)&address, sizeof(sockaddr_in));
if (sentBytes != buffLength){
#if defined(_WIN32)
int lastErr = WSAGetLastError();
printf("failed to send packet (err: %d)\n", lastErr);
#else
printf("failed to send packet.\n");
BNS_SOCKET_ERROR();
#endif
return false;
}
*bytesSent = sentBytes;
return true;
}
bool Socket::StreamDataTo(const void* buffer, int buffLength, int* bytesSent, IPV4Addr dst){
if (protocol != SP_UDP){
printf("\nError: Trying to stream data on a TCP socket, stopping.\n");
return false;
}
sockaddr_in address = dst.ToSockAddr();
int sentBytes = sendto(handle, (const char*)buffer, buffLength, 0, (sockaddr*)&address, sizeof(sockaddr_in));
if (sentBytes != buffLength){
#if defined(_WIN32)
int lastErr = WSAGetLastError();
printf("failed to send packet (err: %d)\n", lastErr);
#else
printf("failed to send packet.\n");
BNS_SOCKET_ERROR();
#endif
return false;
}
*bytesSent = sentBytes;
return true;
}
bool Socket::ReceiveData(void* buffer, int buffLength, int* bytesReceived, IPV4Addr* outAddr){
sockaddr_in from = {};
socklen_t fromLen = sizeof(from);
int receivedBytes = recvfrom(handle, (char*)buffer, buffLength, 0, (sockaddr*)&from, &fromLen);
if (receivedBytes == -1 && errno != 0 && errno != EWOULDBLOCK){
printf("Socket encountered error '%s'\n", strerror(errno));
}
IPV4Addr addr;
addr.addr = from.sin_addr.s_addr;
addr.port = from.sin_port;
*outAddr = addr;
*bytesReceived = receivedBytes;
return receivedBytes > 0;
}
bool Socket::Listen(int backlog){
int retVal = listen(handle, backlog);
if (retVal == 0){
return true;
}
else{
BNS_SOCKET_ERROR();
return false;
}
}
bool Socket::AcceptConnection(Socket* outSocket){
sockaddr_in from = {};
socklen_t fromLen = sizeof(from);
int rv = (int)accept(handle, (sockaddr*)&from, &fromLen);
if (rv < 0){
return false;
}
else{
*outSocket = *this;
outSocket->handle = rv;
outSocket->SetBlocking(blockingType);
IPV4Addr addr;
addr.addr = from.sin_addr.s_addr;
addr.port = from.sin_port;
outSocket->destination = addr;
return true;
}
}
bool Socket::Destroy(){
#if defined(_WIN32)
// TODO: close for windows
closesocket(handle);
return true;
#else
close(handle);
return true;
#endif
}
bool isSocketSystemInitialised = false;
bool StartUpSocketSystem(){
#if defined(_WIN32)
WSADATA WsaData;
return WSAStartup(MAKEWORD(2,2), &WsaData) == NO_ERROR;
#else
return true;
#endif
}
bool ShutdownSocketSystem(){
return true;
}
#if defined(SOCKET_TEST_MAIN)
CREATE_TEST_CASE("socket...does this work?") {
if(!StartUpSocketSystem()){
printf("Failed to init socket system, exiting.\n");
return -1;
}
Socket sock1;
sock1.Create(SP_UDP, SBT_NonBlocking);
sock1.Bind(12245);
Socket sock2;
sock2.Create(SP_UDP, SBT_NonBlocking);
sock2.Bind(12243);
sock1.Connect(sock2.source);
const char* dataToSend = "Hello World";
int bytesSent = 0;
sock1.SendData(dataToSend, strlen(dataToSend)+1, &bytesSent);
usleep(1000);
char packet[256];
int bytesReceived = 0;
int timeout = 0;
while (bytesReceived <= 0){
IPV4Addr addr;
sock2.ReceiveData(packet, sizeof(packet), &bytesReceived, &addr);
usleep(1000);
timeout++;
if (timeout > 10){
break;
}
}
printf("Received '%s' from socket.\n", packet);
if (strcmp(packet, dataToSend) != 0){
return -1;
}
return 0;
}
#endif