-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServer.cpp
More file actions
213 lines (161 loc) · 6.16 KB
/
Server.cpp
File metadata and controls
213 lines (161 loc) · 6.16 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
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
/* ===============================
Server.cpp (Multithreaded Server)
=============================== */
#include "Server.h"
NetworkConfig netConfig("192.168.0.0", 24);
void Server::initializeNetworkConfig() {
std::shared_ptr<TV> tv = std::make_shared<TV>();
std::shared_ptr<Refrigerator> refrigerator = std::make_shared<Refrigerator>();
std::shared_ptr<Light> light = std::make_shared<Light>();
std::shared_ptr<Camera> camera = std::make_shared<Camera>();
std::shared_ptr<Thermostat> thermostat = std::make_shared<Thermostat>();
std::vector<std::pair<int, std::shared_ptr<DeviceType>>> deviceCounts = {
{3, tv}, // 3 TVs
{2, refrigerator}, // 2 Refrigerators
{5, light}, // 5 Lamps
{4, camera}, // 4 Cameras
{1, thermostat}, // 1 Thermostat
};
netConfig.generateSubnets(deviceCounts);
}
void Server::start() {
initializeNetworkConfig();
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
std::cerr << "WSAStartup failed with error: " << result << "\n";
return;
}
SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET) {
std::cerr << "Socket creation failed with error: " << WSAGetLastError() << "\n";
WSACleanup();
return;
}
sockaddr_in serverAddr = {};
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(8080);
serverAddr.sin_addr.s_addr = INADDR_ANY; // Listen on all interfaces
if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
std::cerr << "Bind failed with error: " << WSAGetLastError() << "\n";
closesocket(serverSocket);
WSACleanup();
return;
}
if (listen(serverSocket, 5) == SOCKET_ERROR) {
std::cerr << "Listen failed with error: " << WSAGetLastError() << "\n";
closesocket(serverSocket);
WSACleanup();
return;
}
std::cout << "Server started on port 8080...\n";
while (true) {
SOCKET clientSocket = accept(serverSocket, NULL, NULL);
if (clientSocket == INVALID_SOCKET) {
std::cerr << "Accept failed with error: " << WSAGetLastError() << "\n";
continue;
}
std::thread(&Server::handleClient, this, clientSocket).detach(); // Handle client in a separate thread
}
closesocket(serverSocket);
WSACleanup();
}
Packet Server::parseCommandToPacket(const std::string& command) {
Packet packet;
// Find the last space to separate the source IP from the rest
size_t lastSpace = command.rfind(' ');
if (lastSpace == std::string::npos) {
std::cerr << "Invalid command format: missing source IP.\n";
return packet;
}
std::string mainCommand = command.substr(0, lastSpace); // GET /DEST_IP/.../VALUE
packet.sourceIP = command.substr(lastSpace + 1); // SOURCE_IP
std::istringstream ss(mainCommand);
std::string uri;
ss >> packet.httpMethod >> uri;
if (!uri.empty() && uri[0] == '/') {
uri = uri.substr(1);
}
std::stringstream uriStream(uri);
std::string token;
std::vector<std::string> parts;
while (std::getline(uriStream, token, '/')) {
parts.push_back(token);
}
if (parts.size() > 0) packet.destinationIP = parts[0];
if (parts.size() > 1) packet.deviceFunction = parts[1];
if (parts.size() > 2) packet.subFunction = parts[2];
if (parts.size() > 3) packet.value = parts[3];
return packet;
}
uint32_t ipToUint(const std::string& ip) {
std::istringstream iss(ip);
std::string token;
uint32_t result = 0;
for (int i = 0; i < 4; ++i) {
std::getline(iss, token, '.');
result = (result << 8) | std::stoi(token);
}
return result;
}
bool matchPrefix(uint32_t ip, uint32_t network, int prefixLength) {
uint32_t mask = prefixLength == 0 ? 0 : ~((1 << (32 - prefixLength)) - 1);
return (ip & mask) == (network & mask);
}
Packet Server::routePacket(Packet& packet) {
std::string destIP = packet.destinationIP;
uint32_t destIPNum = ipToUint(destIP);
std::cout << "[Debug] Destination IP: " << destIP << std::endl;
std::shared_ptr<Router> targetRouter = nullptr;
int longestMatch = -1;
std::string bestNextHop;
for (const auto& route : netConfig.getRoutingTable()) {
uint32_t networkNum = ipToUint(route.destinationNetwork);
int prefixLength = route.subnetMaskBits;
std::cout << "[Debug] Checking route -> Destination Network: " << route.destinationNetwork
<< ", Next Hop: " << route.nextHop
<< ", Subnetmasknits: " << route.subnetMaskBits << std::endl;
if (matchPrefix(destIPNum, networkNum, prefixLength)) {
if (prefixLength > longestMatch) {
longestMatch = prefixLength;
bestNextHop = route.nextHop;
}
}
}
if (longestMatch != -1) {
for (const auto& subnet : netConfig.getSubnets()) {
if (subnet->router->ipAddress == bestNextHop) {
Packet response = subnet->router->relayPacket(packet);
return response;
}
}
}
packet.body = "[Server] No matching route found.\n";
packet.status = "502";
return packet;
}
void Server::handleClient(SOCKET clientSocket) {
std::cout << "Handling client in thread: " << std::this_thread::get_id() << "\n";
char buffer[1024] = { 0 };
int bytesReceived = recv(clientSocket, buffer, sizeof(buffer) - 1, 0);
if (bytesReceived == SOCKET_ERROR) {
std::cerr << "recv failed with error: " << WSAGetLastError() << "\n";
closesocket(clientSocket);
return;
}
if (bytesReceived == 0) {
std::cout << "Client disconnected.\n";
closesocket(clientSocket);
return;
}
std::cout << "Received: " << buffer << "\n";
Packet packet = parseCommandToPacket(buffer);
Packet response = routePacket(packet);
send(clientSocket, response.body.c_str(), response.body.length(), 0);
closesocket(clientSocket);
}
int main() {
Server server;
server.start();
return 0;
}