设置connect超时-linux

在Linux平台下,可以通过在connect之前设置SO_SNDTIMO来达到控制连接超时的目的 。简单的写了份测试代码:

[cpp]  view plain copy
  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include <sys/types.h>  
  4. #include <sys/socket.h>  
  5. #include <netinet/in.h>  
  6. #include <errno.h>  
  7. #include <sys/socket.h>  
  8. #include <netinet/in.h>  
  9. #include <arpa/inet.h>  
  10.   
  11. int main(int argc, char *argv[])  
  12. {  
  13.         int fd;   
  14.         struct sockaddr_in addr;  
  15.         struct timeval timeo = {3, 0};   
  16.         socklen_t len = sizeof(timeo);  
  17.   
  18.          fd = socket(AF_INET, SOCK_STREAM, 0);  
  19.          if (argc == 4)  
  20.                  timeo.tv_sec = atoi(argv[3]);  
  21.   
  22.          setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeo, len);  
  23.          addr.sin_family = AF_INET;  
  24.          addr.sin_addr.s_addr = inet_addr(argv[1]);  
  25.          addr.sin_port = htons(atoi(argv[2]));  
  26.   
  27.         if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {  
  28.                 if (errno == EINPROGRESS) {  
  29.                         fprintf(stderr, "timeout/n");  
  30.                         return -1;  
  31.                 }         
  32.                 perror("connect");  
  33.                 return 0;  
  34.         }         
  35.         printf("connected/n");  
  36.   
  37.         return 0;  
  38. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值