WINDOWS环境下设置socket连接超时

35 篇文章 0 订阅

众所周知,在进行网络编程的时候,如果使用系统connect函数,无法设置超时,而在连接一个不存在的主机时,将会一直阻塞。

其实在调用connect函数时,将句柄设置为非阻塞,然后调用select函数,可以达到设置超时的效果。


[cpp]  view plain copy
  1. bool connect(char *host,int port, int timeout)  
  2. {  
  3.     TIMEVAL Timeout;  
  4.     Timeout.tv_sec = timeout;  
  5.     Timeout.tv_usec = 0;  
  6.     struct sockaddr_in address;  /* the libc network address data structure */     
  7.   
  8.     sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);  
  9.   
  10.     address.sin_addr.s_addr = inet_addr(host); /* assign the address */  
  11.     address.sin_port = htons(port);            /* translate int2port num */  
  12.     address.sin_family = AF_INET;  
  13.   
  14.     //set the socket in non-blocking  
  15.     unsigned long iMode = 1;  
  16.     int iResult = ioctlsocket(sock, FIONBIO, &iMode);  
  17.     if (iResult != NO_ERROR)  
  18.     {  
  19.         printf("ioctlsocket failed with error: %ld\n", iResult);  
  20.     }  
  21.   
  22.     if(connect(sock,(struct sockaddr *)&address,sizeof(address))==false)  
  23.     {  
  24.         return false;  
  25.     }     
  26.   
  27.     // restart the socket mode  
  28.     iMode = 0;  
  29.     iResult = ioctlsocket(sock, FIONBIO, &iMode);  
  30.     if (iResult != NO_ERROR)  
  31.     {  
  32.         printf("ioctlsocket failed with error: %ld\n", iResult);  
  33.     }  
  34.   
  35.     fd_set Write, Err;  
  36.     FD_ZERO(&Write);  
  37.     FD_ZERO(&Err);  
  38.     FD_SET(sock, &Write);  
  39.     FD_SET(sock, &Err);  
  40.   
  41.     // check if the socket is ready  
  42.     select(0,NULL,&Write,&Err,&Timeout);  
  43.     if(FD_ISSET(sock, &Write))  
  44.     {  
  45.         return true;  
  46.     }  
  47.   
  48.     return false;  
  49. }  
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值