Added close() calls to all Server constructor fails, also added SO_REUSEADDR

This commit is contained in:
iherman-
2026-05-12 20:38:33 +02:00
parent 78aa891d38
commit d408d08249
2 changed files with 17 additions and 5 deletions

View File

@@ -6,7 +6,7 @@
/* By: iherman- <iherman-@student.42malaga.com +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2026/05/06 17:19:12 by iherman- #+# #+# */
/* Updated: 2026/05/12 19:25:29 by iherman- ### ########.fr */
/* Updated: 2026/05/12 20:34:58 by iherman- ### ########.fr */
/* */
/* ************************************************************************** */
@@ -42,7 +42,6 @@ void echo(User& client, std::istringstream& input)
send(client.getFd(), message.c_str(), message.size(), 0);
}
Server::Server() :
port_(PORT_DEFAULT),
password_("password")
@@ -93,6 +92,13 @@ Server::Server(int port, const std::string& password) :
if (serverSocket_ < 0)
throw std::runtime_error("Failed to create socket");
int opt = 1;
if (setsockopt(serverSocket_, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
{
close(serverSocket_);
throw std::runtime_error("setsockopt failed");
}
struct sockaddr_in addr;
std::memset(&addr, 0, sizeof(addr));
@@ -101,10 +107,16 @@ Server::Server(int port, const std::string& password) :
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(serverSocket_, (struct sockaddr*)&addr, sizeof(addr)))
{
close(serverSocket_);
throw std::runtime_error("Failed to bind");
}
if (listen(serverSocket_, kConnectionQueueLimit))
{
close(serverSocket_); // maybe make an fd class that cleans up automatically using the destructor
throw std::runtime_error("Failed to listen");
}
// Add all new commands to commands_ here
commands_["echo"] = &echo;