timeval tm;
fd_set set;
int error = -1;
int iReceTimeOut = 2000;
int len = sizeof(int);
SOCKET hSocket
1.生成socket
hSocket = socket(AF_INET, SOCK_STREAM, 0);
2.设置套接字为非阻塞模式
unsigned long ul = 1;
ioctlsocket(hSocket , FIONBIO, &ul); //设置为非阻塞模式
3.开始连接目标地
if (INVALID_SOCKET != hSocket) { return false; } hSocket = socket(AF_INET, SOCK_STREAM, 0); if (INVALID_SOCKET == hSocket) { return false; } unsigned long ul = 1; timeval tm; fd_set set; int error = -1; int iReceTimeOut = 2000; int len = sizeof(int); SOCKADDR_IN SocketAddr; memset(&SocketAddr,0,sizeof(SOCKADDR_IN)); SocketAddr.sin_addr.s_addr = inet_addr(pServerIp); SocketAddr.sin_port = htons(iPort); SocketAddr.sin_family = AF_INET; ioctlsocket(hSocket, FIONBIO, &ul); //设置为非阻塞模式 if (SOCKET_ERROR == connect(hSocket, (SOCKADDR *)&SocketAddr, sizeof(SOCKADDR_IN))) { //连接sock5服务器失败 tm.tv_sec = 2; tm.tv_usec = 0; FD_ZERO(&set); FD_SET(hSocket, &set); if( select(hSocket, NULL, &set, NULL, &tm) <= 0) { closesocket(hSocket); hSocket = INVALID_SOCKET; return false; } getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char *)&error, /*(socklen_t *)*/&len); if (error != 0) { closesocket(hSocket); hSocket = INVALID_SOCKET; return false; } } ul = 0; ioctlsocket(hSocket, FIONBIO, &ul); //设置为阻塞模式 setsockopt( hSocket, SOL_SOCKET, SO_RCVTIMEO, ( char * )&iReceTimeOut, sizeof( int ) );
4.最后结束后将套接字再次设置为阻塞模式
ul = 0;
ioctlsocket(hSocket , FIONBIO, &ul); //设置为阻塞模式
5.如果想设置接受超时
setsockopt( hSocket , SOL_SOCKET, SO_RCVTIMEO, ( char * )&iReceTimeOut, sizeof( int ) );