In my program If the server is not reachable the connect function take too much time. So i try to give time out to connect using select(). Now the problem is that when i try to
The first successful select means the connect operation is complete but does not necessarily mean it succeed, from connect man page, you should check SO_ERROR
to make sure it completed successfully
It is possible to select(2) or poll(2) for completion by selecting the socket for writing. After select(2) indicates writability, use getsockopt(2) to read the SO_ERROR option at level SOL_SOCKET to determine whether connect() completed successfully (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual error codes listed here, explaining the reason for the failure).
So in your code you should do something like this:
int ret;
ret=select(sockfd+1, NULL, &wfds, NULL, NULL); //should use timeout
if(ret==1 && getSocketOpt(sockfd, SO_ERROR) ==0) {
return 0; //successfully connected
}
Then, as mentioned in the other answer you should call select again before writing or reading from the socket.