int error = -1; int len = sizeof(int); timeval tm; fd_set set; unsigned long ul = 1; ioctlsocket(Socket, FIONBIO, &ul); // set as non-blocking bool ret = false; if (connect(Socket, (struct sockaddr *)&ServerAddress, sizeof(ServerAddress)) == -1) { tm.tv_sec = 10; // set the timeout. 10s tm.tv_usec = 0; FD_ZERO(&set); FD_SET(Socket, &set); if (select(Socket + 1, NULL, &set, NULL, &tm) > 0) { getsockopt(Socket, SOL_SOCKET, SO_ERROR, (char *)&error, /*(socklen_t *)*/ &len); if (error == 0) ret = true; else ret = false; } else ret = false; } else ret = true; ul = 0; ioctlsocket(Socket, FIONBIO, &ul); // set as blocking if (!ret) { closesocket(Socket); fprintf(stderr, "Cannot Connect the server!/n"); }