Linux connect() timeout

来源:互联网 发布:奔腾预算软件下载 编辑:程序博客网 时间:2024/05/16 10:49

原来我们实现connect()超时基本上都使用unix网络编程一书的非阻塞方式(connect_nonb),今天在网上看到一篇文章,觉得很有意思,转载如下:

 

读Linux内核源码的时候偶然发现其connect的超时参数竟然和用SO_SNDTIMO操作的参数一致:
File: net/ipv4/af_inet.c

    559       timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
    560
    561       if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
    562           /* Error code is set above */
    563           if (!timeo || !inet_wait_for_connect(sk, timeo))
    564               goto out;
    565
    566           err = sock_intr_errno(timeo);
    567           if (signal_pending(current))
    568               goto out;
    569       }
这意味着:在Linux平台下,可以通过在connect之前设置SO_SNDTIMO来达到控制连接超时的目的。简单的写了份测试代码:
[cpp] view plaincopy
  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. }  

使用 ./cmd  ip地址  端口  超时秒数   

(测试的ip和端口必须是不存在的,或者是ip的机器是死掉的,才会出现,否则机器存在而端口不存在会立即返回的)

0 0
原创粉丝点击