The following is the essence of my test fixture -
SetUp()
{
g_listen_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
/* localhost is the server */
bind(g_listen_sock, (struct sockaddr *)&server_addr, sizeof(server_addr));
listen(g_listen_sock, max_connections);
}
testcase()
{
hdl = accept(g_listen_sock, NULL, NULL);
-- send()/recv() data on the socket --
}
TearDown()
{
shutdown(g_listen_sock, SHUT_RDWR);
close(g_listen_sock);
g_listen_sock = INVALID_SOCKET;
}
In the normal use of the application the listening socket is bound only once during the lifetime of the application, however the test setup repeatedly opens and closes the listening socket. The first iteration of the testcase works fine but subsequent iterations fail at the bind() call with errno == 98
i.e. EADDRINUSE.
How do I avoid this situation? The solution ideally wouldn't require me to have a separate test version of the code, for e.g. using SO_REUSEADDR while testing.
P.S. - the same code works fine on Windows, the bind() failure happens on Linux.