Title: WinSock connect() problem. Client thinks it is connected even when Server is down
As of right now, my program incorrectly displays the status of the connecting socket. Because of the if statements seen below, even when the server is down, my friends can access a part of the program which should only be available when successfully connected to the server.
On the client, they are accessing an input (which lets them send a message to the server) even when they are not connected to the server, where the program should have normally told them they failed to connect and would have closed the program.
Here is the code, can you help me fix up this if-statement so that it works properly?
//create the socket
client = socket(AF_INET, SOCK_STREAM, 0);
//set the socket I/O mode
//if iMode = 0, blocking is enabled
//if iMode != 0, non-blocking mode is enabled
u_long iMode = 1;
ioctlsocket(client, FIONBIO, &iMode);
//connect to the server
if( connect( client, (sockaddr*)&server, sizeof(server) ) == SOCKET_ERROR)
{
if( WSAGetLastError() == WSAEWOULDBLOCK)
{
cout << "Attempting to connect.\n";
}
else
{
cout << "Failed to connect to server.\n";
cout << "Error: " << WSAGetLastError() << endl;
WSACleanup();
system("pause");
return 1;
}
}
To offer some help, the connect() SHOULD return WSAEWOULDBLOCK first, as it ATTEMPTS to connect. Eventually it will return 0 for success, or SOCKET_ERROR if it has failed. The error can be determined by the WSAGetLastError() function shown in the else block.
I can't seem to wrap my head around the logic required in order to setup the if-statements correctly after the first WSAEWOULDBLOCK check. Am I supposed to use select()? How do I do that? Thanks for the help!