-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCRecv.cpp
More file actions
93 lines (67 loc) · 2.47 KB
/
CRecv.cpp
File metadata and controls
93 lines (67 loc) · 2.47 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
84
85
86
87
88
89
90
91
92
93
#include <fstream>
#include <netdb.h>
#include <sys/socket.h>
#include <iostream>
#include <netinet/in.h>
#include <thread>
#include <chrono>
#include <unistd.h>
#include "echelonheaders.h"
int clientRecv(Config cfg) {
namespace ch = std::chrono;
bool continuous = cfg.continuous;
double speed = cfg.speed;
const char* passkey = cfg.passkey.c_str();
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET; //IPV4
serverAddress.sin_port = htons(PORT); // set in echelonheaders.h file
struct hostent* host = gethostbyname(cfg.ip.c_str()); // argv[3] is ip or domain
serverAddress.sin_addr.s_addr = *((unsigned long*)host->h_addr); // converts domain to ip
while(connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) >= 0) {
if(passkey != nullptr && strlen(passkey) > 0) {
int passkeyLength = strlen(passkey);
if(passkeyLength <= 0 || passkeyLength > 1024) {
std::cerr << "Invalid passkey lenght\n";
close(clientSocket);
return 1;
}
send(clientSocket, &passkeyLength, sizeof(int), 0);
send(clientSocket, passkey, passkeyLength, 0);
}
int filenameSize;
recv(clientSocket, &filenameSize, sizeof(int), 0);
if(filenameSize <= 0 || filenameSize > 512) {
std::cerr << "Invalid filename lenght\n";
close(clientSocket);
return 1;
}
std::string filename(filenameSize, '\0');
recv(clientSocket, filename.data(), filenameSize, 0);
std::streampos fileSize;
recv(clientSocket, &fileSize, sizeof(int), 0);
std::ofstream file(filename, std::ios::binary);
char buffer[BUFFER_SIZE]; // set in echelonheaders.h file
int bytes_recv;
int sleepDuration;
double MB = 0; // counter
double fileSizeMB = (double)fileSize / 1000000;
std::cout << "Recieving file: " << filename << std::endl;
if(speed > 0) {
sleepDuration = calculateSpeed(speed);
}
std::thread speedometer(BytesPerSecond, std::ref(bytesCounter), std::ref(speedBps), std::ref(running));
while((bytes_recv = recv(clientSocket, buffer, sizeof(buffer), 0)) > 0) {
updateReceiveProgress(file, buffer, bytes_recv, MB, fileSizeMB, bytesCounter, speedBps);
if (speed > 0){
std::this_thread::sleep_for(ch::microseconds(sleepDuration));
}
}
running = false;
speedometer.join();
std::cout << std::endl;
file.close();
}
close(clientSocket);
return 0;
}