设置connect超时

首先设置socket为非阻塞模式

再通过select查询超时

#include "stdafx.h" #include <WINSOCK2.H> #include <stdio.h> #pragma comment(lib,"ws2_32.lib") int main(int argc, char* argv[]) { WSADATA wsaData; if (WSAStartup(MAKEWORD(2,2),&wsaData)!=0) { return -1; } PHOSTENT phst=gethostbyname("www.yahoo.com"); if (!phst) { return -1; } IN_ADDR addr; memmove(&addr,phst->h_addr_list[0],phst->h_length); SOCKADDR_IN Rtaddr; Rtaddr.sin_family=AF_INET; Rtaddr.sin_addr=addr; Rtaddr.sin_port=htons(80); SOCKET s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if (s==INVALID_SOCKET) { return -1; } DWORD dwset=1; int ret=ioctlsocket(s,FIONBIO,(LPDWORD)&dwset); if (ret==SOCKET_ERROR) { return -1; } DWORD start=GetTickCount(); connect(s,(SOCKADDR*)&Rtaddr,sizeof Rtaddr); timeval timeout; fd_set r; FD_ZERO(&r); FD_SET(s,&r); timeout.tv_sec=1; timeout.tv_usec=0; ret=select(0,0,&r,0,&timeout); if (ret<=0) //超时或SOCKET_ERROR { printf("connect error.../n"); } else printf("connect success./n"); printf("time: %d/n",GetTickCount()-start); dwset=0; ret=ioctlsocket(s,FIONBIO,(LPDWORD)&dwset); if (ret==SOCKET_ERROR) { printf("error %d/n",WSAGetLastError()); } closesocket(s); WSACleanup(); return 0; } 

你可能感兴趣的:(socket,tcp,Stream,list)