-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnectCommand.cpp
More file actions
60 lines (52 loc) · 1.67 KB
/
ConnectCommand.cpp
File metadata and controls
60 lines (52 loc) · 1.67 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
//
// Created by duni on 22/12/2019.
//
#include <netinet/in.h>
#include <iostream>
#include <arpa/inet.h>
#include <thread>
#include "ConnectCommand.h"
#include "globalVariables.h"
#include "ExpressionCalculate.h"
#include <algorithm>
void connectClient(int port, string ip) {
int socketId = 0;
struct sockaddr_in serverAddress;
// Create socket
if ((socketId = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
cout << "socket creation error" << endl;
exit(EXIT_FAILURE);
}
// Convert the address
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(port);
const char *ipConst = ip.c_str();
if (inet_pton(AF_INET, ipConst, &serverAddress.sin_addr) <= 0) {
cout << "invalid address" << endl;
exit(EXIT_FAILURE);
}
// Connect to the client
while (connect(socketId, (struct sockaddr *) &serverAddress, sizeof(serverAddress)) < 0) {
}
cout << "connected" << endl;
globalVariables::socketId = socketId;
}
int ConnectCommand::execute(vector<string> params) {
Interpreter *i = new Interpreter();
Expression *answer = nullptr;
// Remove spaces
string::iterator end_pos = remove(params[2].begin(), params[2].end(), ' ');
params[2].erase(end_pos, params[2].end());
// Remove tabs
end_pos = remove(params[2].begin(), params[2].end(), '\t');
params[2].erase(end_pos, params[2].end());
// Calculate the expression of the port
answer = i->interpret(params[2]);
int port = answer->calculate();
string ip = params[1];
ip = ip.substr(1, ip.length() - 2);
// Open the thread
thread threadClient(connectClient, port, ip);
threadClient.join();
return 3;
}