Merge pull request 'Added close() calls to all Server constructor fails, also added SO_REUSEADDR' (#19) from constructor-improvement into main

Reviewed-on: http://gitea.hadi.es/aortigos/ft_irc/pulls/19
This commit is contained in:
2026-05-12 18:39:04 +00:00
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;

View File

@@ -37,13 +37,13 @@ Represents a connected IRC client.
### Second stage
- [✓] Server can handle multiple clients simultaneously
- [ ] Manage SO_REUSEADDR (restarting server fails to bind same port)
- [✓] Manage SO_REUSEADDR (restarting server fails to bind same port)
### Third stage
- [ ] Client has nickname and username
- [✓] Dispatcher (select function for each command)
- [ ] Implement generic parser (extract command and pass args to command function)
- [ ] Dispatcher (select function for each command)
- [ ] Client has nickname and username
- [ ] PASS command for authenticate
### Fourth stage