Hi there!
I would like a little help regarding the following code.

The following code will wait for a non-blocking socket connection, and then wait to receive a certain packet. When the packet arrives, it will do something and then close connection and reinitialize it in order to be able to accept again. The client side closes it's connection also that's why i completely shutdown this one's also.

The problem is that the first time of the loop the operation is successful, but on second attempt, it cannot accept a socket connection and blocks on accept().

On client side i when i try to connect second time, i get a WSAECONNREFUSED error.

I am quite sure that this is the server's side problem because i used a couple of TCP socket testers available online and they all get a connection refused on the second attempt. That's why i didn't post the client side.

while(1)
{

	WSADATA WsaDat;
	if(WSAStartup(MAKEWORD(2,2),&WsaDat)!=0)
	{
		TRACE("---------WSA Initialization failed!----------\r\n");
		WSACleanup();
		return 0;
	}
	
	SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
	if(Socket==INVALID_SOCKET)
	{
		TRACE("---------Socket creation failed.----------\r\n");
		WSACleanup();
		return 0;
	}
					
	SOCKADDR_IN serverInf;
	serverInf.sin_family=AF_INET;
	serverInf.sin_addr.s_addr=INADDR_ANY;
	serverInf.sin_port=htons(2224);

	///TRY TO REUSE ADDRESS
	char reuse_add = '1';
	int reuseerr = setsockopt(Socket, SOL_SOCKET, SO_REUSEADDR, &reuse_add, sizeof (reuse_add));
	///TRY TO REUSE ADDRESS
					
	if(bind(Socket,(SOCKADDR*)(&serverInf),sizeof(serverInf))==SOCKET_ERROR)
	{
		TRACE("------------Unable to bind socket!-----------\r\n");
		WSACleanup();
		return 0;
	}
		
	int err = listen(Socket,1);
					
	SOCKET TempSock=SOCKET_ERROR;
	while(TempSock==SOCKET_ERROR)
	{
		TRACE("-----------Waiting for incoming connections...-----------\r\n");
		TempSock=accept(Socket,NULL,NULL);
	}
	
	
	// If iMode!=0, non-blocking mode is enabled.
	u_long iMode=1;
	ioctlsocket(Socket,FIONBIO,&iMode);
					
	Socket=TempSock;
	TRACE("---------------Client connected!----------------\r\n");

	while(1)
	{
		char buffer[1000];
		memset(buffer,0,999);
	
		recv(Socket,buffer,1000,0);
		if (strstr("MY_PACKET",buffer)!=NULL)
		{
			TRACE("---------------MY_PACKET RECEIVED!!!---------------------");
			break;
		}
		Sleep(30);
	}

	//////////////////////DO SOME STUFF I WANT
	Sleep(100);

	shutdown(Socket,SD_BOTH);
	closesocket(Socket);
	WSACleanup(); // NOT NECESSARY???


}

My guess :
1) setsockopt() with SO_REUSEADDR option is not working correctly because i am not sure if i use it correctly.
2) Although i use shutdown and closesocket, the connection is not terminated correctly?

Anyway after a lot of debugging i couldn't come to an answer.

Thanks in advance!

Dani AI

Generated

Short, practical summary and fixes (ties to and )

The root cause was structural: the server creates the listening socket inside every loop iteration and then reassigns the same variable to the accepted client socket, which discards the listening-socket handle. As said, the listening socket should stay alive and accept multiple clients; don’t overwrite its handle with the accepted socket. Also avoid calling WSACleanup inside the per-connection loop — call WSAStartup once on process start and WSACleanup once on exit.

Concrete, safe changes to make

  • Create the listening socket once, call listen(), then loop over accept() calls. Close only the client socket returned by accept().
  • Make a socket non-blocking on the socket you actually want non-blocking (the client socket after accept or the listening socket before accept if you want non-blocking accept). Example usages:
BOOL reuse = TRUE;
setsockopt(listenSock, SOL_SOCKET, SO_REUSEADDR, (char*)&reuse, sizeof(reuse));
u_long mode = 1;
ioctlsocket(clientSock, FIONBIO, &mode); // make the accepted socket non-blocking
  • Check every return value and log WSAGetLastError() when a call fails.

Debugging checklist that would have sped diagnosis

  • Run netstat/tcpview while reproducing the problem to see whether the server is actually listening or whether the port is in TIME_WAIT.
  • Remember that some custom clients reuse a local port or close improperly; external TCP testers often behave differently, so a tester working does not guarantee your client is correct.
  • Fix obvious bugs in the receive loop (for example, use strstr(buffer, "MY_PACKET"), not strstr("MY_PACKET", buffer)).
  • Avoid busy-waiting on accept/recv; use blocking accept() in a dedicated thread or use select()/WSAEventSelect for scalable, efficient waiting.

If you keep the listening socket persistent and avoid WSACleanup/variable reuse between accepts you’ll avoid the “connection refused on second attempt” behavior.

Recommended Answers

All 3 Replies

This is a quite unusual way to serve connections. You don't need to shutdown a listening socket; the same one will accept new connections as many times as you want:

listen(serverSocket, 1);
    while(1) {
        clientSocket = accept(serverSocket, 0, 0);
        do_stuff(clientSocket);
        shutdown(clientSocket, SD_BOTH);
        closeSocket(clientSocket);
    }

In your code, after the line 51 you lose the handle to the listening socket forever. It is not affected by shutdown/closesocket anymore. The socket object is still sitting there interfering with a next one you are trying to create.

commented: Useful answer +2

Thanks for the answer. I have no experience with socket programming so my code is mostly from tutorials.

I changed my code but still i get the same error when connecting with my client, but not with an external TCP tester i downloaded. Now it seems that i should change my client.

I think that my client shouldn't terminate/destroy the socket either but it's really hard to change the structure of my client now..
:(

I will try to work around this and if i find anything intersting i will post it.
Else, i will just mark this thread as solved sooner or later..

Any other suggestions still welcome..

Thanks!
:)

For what is worth i switched to udp sockets and solved my problem using the following library which i found extremely helpful.

Practical Sockets

Thanks for the help!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.