C connect实现Timeout效果(Windows)
2021-04-23 17:59
标签:sig etc socket close for const 效果 get struct C connect实现Timeout效果(Windows) 标签:sig etc socket close for const 效果 get struct 原文地址:http://www.cnblogs.com/Jacket-K/p/7992783.htmlint SocketClient::connectTimeOutForWin(SOCKET &connect_fd, const int &timeout, const sockaddr_in &server)
{
int error=-1, len;
len = sizeof(int);
timeval tm;
fd_set set;
unsigned long ul = 1;
//设置为非阻塞模式
ioctlsocket(connect_fd,FIONBIO,&ul);
bool ret = false;
if( connect(connect_fd, (struct sockaddr *)&server, sizeof(struct sockaddr)) == -1)
{
tm.tv_sec = timeout;
tm.tv_usec = 0;
FD_ZERO(&set);
FD_SET(connect_fd, &set);
if( select(-1, NULL, &set, NULL, &tm) > 0)
{
getsockopt(connect_fd, SOL_SOCKET, SO_ERROR, (char*)&error, &len);
if(error == 0) ret = true;
else ret = false;
} else ret = false;
}
else ret = true;
ul = 0;
//设置为阻塞模式
ioctlsocket(connect_fd,FIONBIO,&ul);
if(!ret){
closesocket(connect_fd);
// fprintf(stderr,"Connect server fail in WIN\n");
}
return ret;
}
文章标题:C connect实现Timeout效果(Windows)
文章链接:http://soscw.com/essay/78589.html