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!