From 66ccc52ee0f07adacd8aad823f2d0a30952c6f32 Mon Sep 17 00:00:00 2001 From: cflip Date: Sat, 17 Sep 2022 16:38:04 -0600 Subject: Set SO_REUSEADDR and SO_REUSEPORT socket options This allows the server to reuse the same address and port when repeatedly running and stopping the server while testing things instead of quitting with the "Address already in use" error. --- src/ServerConnection.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/ServerConnection.cpp b/src/ServerConnection.cpp index f9eb666..d9e0203 100644 --- a/src/ServerConnection.cpp +++ b/src/ServerConnection.cpp @@ -5,7 +5,6 @@ #include #include #include -#include #include #include #include @@ -21,11 +20,14 @@ static void error_and_die(const char* message) ServerConnection::ServerConnection(int port) { sockaddr_in address; + int socket_options = 1; if ((m_socket_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) error_and_die("Failed to create socket"); - bzero(&address, sizeof(address)); + if (setsockopt(m_socket_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &socket_options, sizeof(socket_options))) + error_and_die("setsockopt"); + address.sin_family = AF_INET; address.sin_addr.s_addr = htonl(INADDR_ANY); address.sin_port = htons(port); -- cgit v1.2.3