Linux下Socket连接超时的一种实现方法(2)

分类: 桌面应用   出处:iocblog整理  更新时间:2008-12-17   添加到收藏  

  呵呵,引子似乎太长了点儿。读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来达到控制连接超时的目的。简单的写了份测试代码:

 


#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>

int main(int argc, char *argv[])
{
        int fd;
        struct sockaddr_in addr;
        struct timeval timeo = {3, 0};
        socklen_t len = sizeof(timeo);

        fd = socket(af_inet, sock_stream, 0);
        if (argc == 4)(来源 www.iocblog.net)
                timeo.tv_sec = atoi(argv[3]);
        setsockopt(fd, sol_socket, so_sndtimeo, &timeo, len);
        addr.sin_family = af_inet;
        addr.sin_addr.s_addr = inet_addr(argv[1]);
        addr.sin_port = htons(atoi(argv[2]));
        if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
                if (errno == einprogress) {
                        fprintf(stderr, "timeout ");
                        return -1;
                }
                perror("connect");
                return 0;
        }
        printf("connected ");

        return 0;
}


  执行结果:

 

xiaosuo@gentux perl $ ./a.out 10.16.101.1 90
1180290583
timeout
1180290586
xiaosuo@gentux perl $ ./a.out 10.16.101.1 90 2
1180290590
timeout
1180290592
 

 

上一页 [1] [2]


Tag: Socket



文章整理:iocblog
版权申明:本站文章均来自网络,如有侵权,请联系我们,我们收到后立即删除,谢谢!
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有。