summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorcflip <cflip@cflip.net>2022-09-17 16:38:04 -0600
committercflip <cflip@cflip.net>2022-09-17 16:38:04 -0600
commit66ccc52ee0f07adacd8aad823f2d0a30952c6f32 (patch)
tree37cc5746ed6f5f766bed94ada77b8420426a7de6
parent0a8454a508beee7c0dc45d906b13e6fc81342eba (diff)
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.
-rw-r--r--src/ServerConnection.cpp6
1 files 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 <signal.h>
#include <unistd.h>
#include <arpa/inet.h>
-#include <strings.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <netdb.h>
@@ -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);