From 5b2c7eaac4405268195d41ef7ba41a67fe09519f Mon Sep 17 00:00:00 2001 From: Dimitrios Siganos Date: Mon, 30 Jun 2025 22:30:47 +0100 Subject: [PATCH] Set the SO_REUSEADDR socket option of the listening socket This allows the server to be restarted quickly when the listening socket is in TIME_WAIT state, which happens often whilst debugging. Signed-off-by: Dimitrios Siganos --- TPMCmd/Simulator/src/TcpServer.c | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/TPMCmd/Simulator/src/TcpServer.c b/TPMCmd/Simulator/src/TcpServer.c index 34277ab2..d1d8df01 100644 --- a/TPMCmd/Simulator/src/TcpServer.c +++ b/TPMCmd/Simulator/src/TcpServer.c @@ -39,6 +39,7 @@ static int CreateSocket( { struct sockaddr_in MyAddress; int res; + int optval = 1; // // Initialize Winsock #ifdef _MSC_VER @@ -58,6 +59,16 @@ static int CreateSocket( WSAGetLastError()); return -1; } + + // Set the SO_REUSEADDR socket option to allow the socket to be reused and restarted quickly + // when the listening socket is in TIME_WAIT state, which happens often when debugging. + if(setsockopt(*ListenSocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&optval, sizeof(optval)) < 0) + { + printf("setsockopt SO_REUSEADDR failed. Error is 0x%x\n", WSAGetLastError()); + closesocket(*ListenSocket); + return -1; + } + // bind the listening socket to the specified port ZeroMemory(&MyAddress, sizeof(MyAddress)); MyAddress.sin_port = htons((unsigned short)PortNumber);