/* Checks socket connection and wait if it is not connected. It should be called just after connect.  */
static int Check_Connect_And_Wait_Connection(SOCKET sock, int connect_res)
/* Checks socket connection and wait if it is not connected. It should be called just after connect.  */
static int Check_Connect_And_Wait_Connection(SOCKET sock, int connect_res)
{
	struct timeval tmvTimeout = {DEFAULT_TCP_CONNECT_TIMEOUT, 0};
	int result;
	fd_set fdSet;
	FD_ZERO(&fdSet);
	FD_SET(sock, &fdSet);
	if (connect_res < 0) {
		if (EINPROGRESS == errno ) {
			result = select(sock + 1, NULL, &fdSet, NULL, &tmvTimeout);
			if (result < 0) {
				return -1;
			} else if (result == 0) {
				return -1;
			} else {
				int valopt = 0;
				socklen_t len = sizeof(valopt);
				if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (void *) &valopt, &len) < 0) {
					return -1;
				} else if (valopt) {
					return -1;
				}
			}
		}
	}
	return 0;
}