-
Notifications
You must be signed in to change notification settings - Fork 1
/
udp.cpp
539 lines (454 loc) · 15.2 KB
/
udp.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <cstring>
#include <memory>
#include <iostream>
#include <string>
#include "udp.hpp"
#include "util.hpp"
///////////////////////////////////////////////////////////
///////////////// NON CLASS FUNCTIONS /////////////////////
///////////////////////////////////////////////////////////
int getFileSize(FILE *file);
void zerosDatagram (Datagram* dg);
///////////////////////////////////////////////////////////
//////////////// END NON CLASS FUNCTIONS //////////////////
///////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/////////////////////// UDPServer /////////////////////////
///////////////////////////////////////////////////////////
UDPServer::UDPServer(){}
UDPServer::UDPServer(int port){
int socketd = socket(AF_INET, SOCK_DGRAM, 0);
if (socketd == -1){
std::cout << "[Error] Could not open socket." << std::endl;
}
struct sockaddr_in sockaddr;
sockaddr.sin_family = AF_INET;
sockaddr.sin_port = htons(port);
sockaddr.sin_addr.s_addr = INADDR_ANY;
bzero(&(sockaddr.sin_zero), 8);
socketDesc = socketd;
socketAddrLocal = sockaddr;
socketAddrRemote = sockaddr;
}
UDPServer::~UDPServer(void){
::close(this->socketDesc);
}
void UDPServer::_bind(){
if (bind(socketDesc, (struct sockaddr *) & socketAddrLocal, sizeof(struct sockaddr)) < 0){
std::cout << "[Error] could not bind the given socket. Is adress already bound?" << std::endl;
exit(0);
}
}
udpconnection_ptr UDPServer::accept() {
recDatagram();
int port = generatePort();
Datagram* recvDg = getRecvbuffer();
Datagram acceptDatagram;
zerosDatagram(&acceptDatagram);
acceptDatagram.type = ACCEPT;
acceptDatagram.seqNumber = port;
int sent = sendDatagram(acceptDatagram);
udpconnection_ptr udpconnection(new UDPConnection(port, socketAddrRemote, socketAddrLocal));
socketAddrRemote.sin_addr.s_addr = INADDR_ANY;
bzero(&(socketAddrRemote.sin_zero), 8);
return udpconnection;
}
///////////////////////////////////////////////////////////
/////////////////////// UDPClient /////////////////////////
///////////////////////////////////////////////////////////
UDPClient::UDPClient(){}
UDPClient::UDPClient(int port, std::string ip) {
int socketd = 0;
if ((socketd = socket(AF_INET, SOCK_DGRAM, 0)) == -1){
std::cout << "[Error] Could not open socket." << std::endl;
}
struct hostent* server_host = gethostbyname(ip.c_str());
if (server_host == NULL) {
std::cout << "[Error] Host not found." << std::endl;
exit(0);
}
struct sockaddr_in sockaddr;
sockaddr.sin_family = AF_INET;
sockaddr.sin_port = htons(port);
sockaddr.sin_addr = *((struct in_addr *)server_host->h_addr);
bzero(&(sockaddr.sin_zero), 8);
socketDesc = socketd;
socketAddrRemote = sockaddr;
}
UDPClient::~UDPClient(void){
::close(this->socketDesc);
}
int UDPClient::connect(){
Datagram connectDatagram;
zerosDatagram(&connectDatagram);
connectDatagram.type = CONNECT;
connectDatagram.seqNumber = -1;
int sent = sendDatagram(connectDatagram);
return sent;
}
int UDPClient::waitResponse(){
recDatagram();
if (getRecvbuffer()->type == ACCEPT){
Datagram* received = getRecvbuffer();
//std::cerr << "port = " << received->seqNumber << '\n';
//std::cerr << "htons(port) = " << htons(received->seqNumber) << '\n';
socketAddrRemote.sin_port = htons(received->seqNumber);
socketAddrLocal.sin_port = htons(received->seqNumber);
bzero(&(socketAddrRemote.sin_zero), 8);
bzero(&(socketAddrLocal.sin_zero), 8);
::close(this->socketDesc);
int socketd = 0;
if ((socketd = socket(AF_INET, SOCK_DGRAM, 0)) == -1){
std::cout << "[Error] Could not open socket." << std::endl;
}
socketDesc = socketd;
return ACCEPT;
}
return REJECT;
}
struct sockaddr_in* UDPSocket::getAddr(){
return &socketAddrLocal;
}
int UDPSocket::getSocketDesc(){
return socketDesc;
}
///////////////////////////////////////////////////////////
///////////////////// UDPConnection ///////////////////////
///////////////////////////////////////////////////////////
UDPConnection::UDPConnection(){}
UDPConnection::UDPConnection(int port, sockaddr_in socketAddrRemote, sockaddr_in socketAddrLocal) {
this->socketAddrLocal = socketAddrLocal;
this->socketAddrRemote = socketAddrRemote;
this->socketAddrRemote.sin_port = htons(port);
this->socketAddrLocal.sin_port = htons(port);
bzero(&(this->socketAddrLocal.sin_zero), 8);
bzero(&(this->socketAddrRemote.sin_zero), 8);
//std::cerr << "port = " << port << '\n';
//std::cerr << "htons(port) = " << htons(port) << '\n';
if ((this->socketDesc = socket(AF_INET, SOCK_DGRAM, 0)) == -1){
std::cout << "[Error] Could not open a new socket for connection." << std::endl;
}
if (bind(socketDesc, (struct sockaddr *) & this->socketAddrLocal, sizeof(struct sockaddr)) < 0){
std::cout << "[Error] could not bind the given socket. Is adress already bound?" << std::endl;
}
}
struct sockaddr_in* UDPConnection::getAddrRemote(){
return &socketAddrRemote;
}
void UDPConnection::close() {
}
int UDPConnection::sendDatagram(Datagram &dg) {
socklen_t socketSize = sizeof(socketAddrRemote);
int status = 0;
Datagram ack;
Datagram senddg;
zerosDatagram(&senddg);
senddg.type = htonl(dg.type);
senddg.seqNumber = htonl(dg.seqNumber);
senddg.size = htonl(dg.size);
memcpy(senddg.data, dg.data, DATASIZE);
zerosDatagram(&ack);
//0.3 seconds timeout on socket recv
struct timeval read_timeout;
read_timeout.tv_sec = 0;
read_timeout.tv_usec = 300000;
setsockopt(this->getSocketDesc(), SOL_SOCKET, SO_RCVTIMEO, &read_timeout, sizeof read_timeout);
while(true){
status = sendto(getSocketDesc(),
(char*) &senddg,
DGRAMSIZE,
0,
(struct sockaddr *) &socketAddrRemote,
socketSize
);
if (status >= 0){
socklen_t socketSize = sizeof(socketAddrRemote);
recvfrom(getSocketDesc(),
(void*) &ack,
DGRAMSIZE,
0,
(struct sockaddr *) &socketAddrRemote,
&socketSize
);
if (ntohl(ack.type) == ACK && ack.seqNumber == dg.seqNumber){
break;
}
} else{
std::cout << "[Error] Sending datagram." << std::endl;
}
}
return status;
}
int UDPConnection::sendDatagramMaxTries(Datagram &dg, int maxTries) {
socklen_t socketSize = sizeof(socketAddrRemote);
int status = 0, tries = 0;
Datagram ack;
zerosDatagram(&ack);
//0.3 seconds timeout on socket recv
struct timeval read_timeout;
read_timeout.tv_sec = 0;
read_timeout.tv_usec = 300000;
setsockopt(this->getSocketDesc(), SOL_SOCKET, SO_RCVTIMEO, &read_timeout, sizeof read_timeout);
while(true){
status = sendto(getSocketDesc(),
(char*) &dg,
DGRAMSIZE,
0,
(struct sockaddr *) &socketAddrRemote,
socketSize
);
if (status >= 0){
socklen_t socketSize = sizeof(socketAddrRemote);
recvfrom(getSocketDesc(),
(void*) &ack,
DGRAMSIZE,
0,
(struct sockaddr *) &socketAddrRemote,
&socketSize
);
if (ack.type == ACK && ack.seqNumber == dg.seqNumber){
break;
}
tries++;
if (tries > maxTries){
return TIMEOUT;
}
} else {
std::cout << "[Error] Sending datagram." << std::endl;
}
}
return status;
}
int UDPConnection::recDatagram(){
socklen_t socketSize = sizeof(socketAddrRemote);
struct timeval read_timeout;
read_timeout.tv_sec = 0;
read_timeout.tv_usec = 0;
setsockopt(socketDesc,
SOL_SOCKET, SO_RCVTIMEO,
&read_timeout,
sizeof(read_timeout)
);
int status = recvfrom(getSocketDesc(),
&recvbuffer,
DGRAMSIZE,
0,
(struct sockaddr *) &socketAddrRemote,
&socketSize
);
if (status < 0){
std::cout << "[Error] Could not receive Datagram." << std::endl;
} else {
Datagram* received = (Datagram*) &recvbuffer;
Datagram ack;
zerosDatagram(&ack);
ack.type = htonl(ACK);
ack.seqNumber = htonl(received->seqNumber);
socklen_t socketFromSize = sizeof(socketAddrRemote);
sendto(socketDesc,
(void*) &ack,
DGRAMSIZE,
0,
(struct sockaddr *) &socketAddrRemote,
socketFromSize
);
}
Datagram* received = (Datagram*) &recvbuffer;
received->type = ntohl(received->type);
received->seqNumber = ntohl(received->seqNumber);
received->size = ntohl(received->size);
return status;
}
int UDPConnection::recDatagramTimeOut(int timeOut){
socklen_t socketSize = sizeof(socketAddrRemote);
struct timeval read_timeout;
read_timeout.tv_usec = 0;
read_timeout.tv_sec = timeOut;
setsockopt(socketDesc,
SOL_SOCKET, SO_RCVTIMEO,
&read_timeout,
sizeof(read_timeout)
);
int status = recvfrom(getSocketDesc(),
&recvbuffer,
DGRAMSIZE,
0,
(struct sockaddr *) &socketAddrRemote,
&socketSize
);
if (status < 0){
std::cout << "[Error] Could not receive Datagram." << std::endl;
} else {
Datagram* received = (Datagram*) &recvbuffer;
Datagram ack;
zerosDatagram(&ack);
ack.type = ACK;
ack.seqNumber = received->seqNumber;
socklen_t socketFromSize = sizeof(socketAddrRemote);
sendto(socketDesc,
(void*) &ack,
DGRAMSIZE,
0,
(struct sockaddr *) &socketAddrRemote,
socketFromSize
);
}
return status;
}
int UDPConnection::sendString(std::string str){
char* message = const_cast<char*>(str.c_str());
int len = str.size();
int status = sendMessage(message, len);
return status;
}
std::string UDPConnection::receiveString(){
char* c_message = NULL;
c_message = receiveMessage();
std::string message = std::string(c_message);
free(c_message);
return message;
}
int UDPConnection::sendMessage(char* message, int length){
// std::cerr << "<sendMessage Start>" << '\n';
int numDatagrams = (length/DATASIZE)+1;
if ((length%DATASIZE) == 0) {
numDatagrams -= 1;
}
Datagram messageDatagram;
zerosDatagram(&messageDatagram);
messageDatagram.type = MESSAGE;
messageDatagram.seqNumber = 0;
messageDatagram.size = length;
int status = sendDatagram(messageDatagram);
if(status > 0){
int seqNumber;
for(seqNumber=0; seqNumber<numDatagrams; seqNumber++){
zerosDatagram(&messageDatagram);
messageDatagram.type = DATAGRAM;
messageDatagram.seqNumber = seqNumber;
messageDatagram.size = numDatagrams;
memcpy((void *) messageDatagram.data,
(void *) (message + DATASIZE*seqNumber),
DATASIZE
);
sendDatagram(messageDatagram);
}
}
// std::cerr << "<sendMessage End>" << '\n';
return status;
}
long UDPConnection::getRecvMessageSize(){
return recvMessageSize;
}
char* UDPConnection::receiveMessage(){
recDatagram();
Datagram* received = getRecvbuffer();
if (received->type != MESSAGE){
std::cout << "[Error] Expected a message, got a non-message." << std::endl;
return NULL;
}
uint32_t receivedMessageSize = received->size;
int numDatagrams = (receivedMessageSize/DATASIZE)+1;
if (receivedMessageSize%DATASIZE == 0){
numDatagrams--;
}
char* receivedMessage = (char*) malloc(numDatagrams * DATASIZE);
int seqNumber;
for(seqNumber=0; seqNumber<numDatagrams; seqNumber++){
recDatagram();
memcpy((receivedMessage + DATASIZE * seqNumber),
received->data,
DATASIZE
);
}
recvMessageSize = receivedMessageSize;
return receivedMessage;
}
int UDPConnection::sendFile(FILE* file){
int fileSize = getFileSize(file);
int lastDatagramSize = fileSize%DATASIZE;
Datagram fileDatagram;
zerosDatagram(&fileDatagram);
fileDatagram.type = DATAFILE;
fileDatagram.seqNumber = 0;
fileDatagram.size = lastDatagramSize;
int status = sendDatagram(fileDatagram);
if(status < 0){
return -1;
std::cout << "[Error] Could not send sendFile request." << std::endl;
}
char buffer[DATASIZE] = {0};
int seqNumber = 0;
int reading = 1;
while (reading == 1) {
reading = fread(buffer, DATASIZE, 1, file);
zerosDatagram(&fileDatagram);
if (reading == 1){
fileDatagram.type = DATAGRAM;
fileDatagram.seqNumber = seqNumber++;
fileDatagram.size = 0;
memcpy((void *) fileDatagram.data,
(void *) buffer,
DATASIZE
);
}
else{
fileDatagram.type = ENDFILE;
fileDatagram.seqNumber = seqNumber++;
fileDatagram.size = 0;
memcpy((void *) fileDatagram.data,
(void *) buffer,
lastDatagramSize
);
}
sendDatagram(fileDatagram);
memset(&buffer, 0, DATASIZE);
}
return status;
}
int UDPConnection::receiveFile(FILE* file){
int receivedFile = recDatagram();
Datagram* received = getRecvbuffer();
if (received->type != DATAFILE){
std::cout << "[Error] Expected a file, got a non-file." << std::endl;
return -1;
}
int lastDatagramSize = received->size;
int size = DATASIZE;
int seqNumber = 0;
while(received->type != ENDFILE){
recDatagram();
if(seqNumber == received->seqNumber){
if (received->type == ENDFILE){
size = lastDatagramSize;
}
fwrite(received->data, size, 1, file);
seqNumber++;
}
}
return receivedFile;
}
Datagram* UDPConnection::getRecvbuffer(){
return (Datagram*) &recvbuffer;
}
bool UDPConnection::isConnected(){
return this->connected;
}
int getFileSize(FILE *file) {
fseek(file, 0L, SEEK_END);
int fileSize = ftell(file);
rewind(file);
return fileSize;
}
void zerosDatagram (Datagram* dg){
memset(dg, '\0', DGRAMSIZE);
}