转自点击打开链接http://www.cnblogs.com/zhuyf87/archive/2012/12/26/2833832.html
bool ConnectWithTimeout(SOCKET socket, char * host, int port, int timeout)
{TIMEVAL timeval = {0};
timeval.tv_sec = timeout;
timeval.tv_usec = 0;
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = htons(port);
address.sin_addr.s_addr = inet_addr(host);
if(address.sin_addr.s_addr == INADDR_NONE)
return false;
// set the socket in non-blocking
unsigned long mode = 1;
int result = ioctlsocket(socket, FIONBIO, &mode);
if (result != NO_ERROR)
printf("ioctlsocket failed with error: %ld\n", result);
connect(socket, (struct sockaddr *)&address, sizeof(address));
// restart the socket mode
mode = 0;
result = ioctlsocket(socket, FIONBIO, &mode);
if (result != NO_ERROR)
printf("ioctlsocket failed with error: %ld\n", result);
fd_set Write, Err;
FD_ZERO(&Write);
FD_ZERO(&Err);
FD_SET(socket, &Write);
FD_SET(socket, &Err);
// check if the socket is ready
select(0, NULL, &Write, &Err, &timeval);
if(FD_ISSET(socket, &Write))
return true;
return false;
}