@@ -133,6 +133,7 @@ void UnixSocket::bindSocket()
133
133
std::cout << " Error code: " + errno << std::endl;
134
134
exit (EXIT_FAILURE);
135
135
}
136
+ this ->setSocketTimeout (this ->server_socket , 5 );
136
137
LOG_INFO (logger, " Binding done! Listening to connections ..." );
137
138
}
138
139
@@ -188,6 +189,8 @@ void UnixSocket::acceptConnection(SOCKET &client_socket, void *client_address)
188
189
throw IPBlackListedException ();
189
190
}
190
191
}
192
+
193
+ this ->client_sockets .push_back (client_socket);
191
194
}
192
195
193
196
ssize_t UnixSocket::receiveData (SOCKET client_socket, char *buffer, unsigned int buffer_size)
@@ -209,7 +212,13 @@ void UnixSocket::sendData(SOCKET client_socket, const void *buffer, unsigned int
209
212
210
213
void UnixSocket::closeSocket ()
211
214
{
212
- std::cout << " Closing socket ..." << std::endl;
215
+ LOG_INFO (logger, " Cleaning up client sockets ..." );
216
+ for (auto &it : this ->client_sockets )
217
+ {
218
+ this ->closeSocket (it);
219
+ }
220
+
221
+ LOG_INFO (logger, " Closing socket ..." );
213
222
if (shutdown (this ->server_socket , SHUT_RDWR) == -1 )
214
223
{
215
224
perror (" An error occurred while shutting down the socket: " );
@@ -218,7 +227,7 @@ void UnixSocket::closeSocket()
218
227
}
219
228
if (close (this ->server_socket ) == 0 )
220
229
{
221
- std::cout << " Socket closed!" << std::endl ;
230
+ LOG_INFO (logger, " Socket closed!" ) ;
222
231
exit (EXIT_SUCCESS);
223
232
}
224
233
else
@@ -231,14 +240,36 @@ void UnixSocket::closeSocket()
231
240
232
241
void UnixSocket::closeSocket (SOCKET client_socket)
233
242
{
243
+ if (shutdown (client_socket, SHUT_RDWR) == -1 )
244
+ {
245
+ perror (" An error occurred while shutting down the socket: " );
246
+ std::cout << " Error code: " + errno << std::endl;
247
+ exit (EXIT_FAILURE);
248
+ }
234
249
close (client_socket);
250
+
251
+ auto it = std::find (this ->client_sockets .begin (), this ->client_sockets .end (), client_socket);
252
+
253
+ // Check if element was found before erasing
254
+ if (it != this ->client_sockets .end ())
255
+ {
256
+ this ->client_sockets .erase (it);
257
+ }
235
258
}
236
259
237
260
std::string UnixSocket::getClientIp ()
238
261
{
239
262
return this ->client_ip ;
240
263
}
241
264
265
+ void UnixSocket::setSocketTimeout (SOCKET sock, int timeoutSec)
266
+ {
267
+ struct timeval tv;
268
+ tv.tv_sec = timeoutSec; // Seconds
269
+ tv.tv_usec = 0 ; // Microseconds
270
+ setsockopt (sock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof tv);
271
+ }
272
+
242
273
UnixSocket::~UnixSocket () {}
243
274
244
275
#endif
0 commit comments