在linux下玩转带有超时时间的connect函数

吾爱主题 阅读:171 2024-04-05 15:04:56 评论:0

在之前的文章中,我们在Windows下玩过带有超时时间的,本文我们在linux下来玩。在某次面试中,还被遇到了这个问题,有意思。

直接上客户端代码:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <errno.h> #include <malloc.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/ioctl.h> #include <stdarg.h> #include <fcntl.h> #include <time.h> int main( int argc, char *argv[]) // 注意输入参数, 带上ip和port {    int sockClient = socket(AF_INET, SOCK_STREAM, 0);    struct sockaddr_in addrSrv;    addrSrv.sin_addr.s_addr = inet_addr(argv[1]);    addrSrv.sin_family = AF_INET;    addrSrv.sin_port = htons( atoi (argv[2]));   fcntl(sockClient, F_SETFL, fcntl(sockClient, F_GETFL, 0)|O_NONBLOCK);    int iRet = connect(sockClient, ( const struct sockaddr *)&addrSrv, sizeof ( struct sockaddr_in));   printf ( "connect iRet is %d, errmsg:%s\n" , iRet, strerror ( errno )); // 返回-1不一定是异常   if (iRet != 0)   {     if ( errno != EINPROGRESS)   {    printf ( "connect error:%s\n" , strerror ( errno ));   }     else   {    struct timeval tm = {5, 0};    fd_set wset, rset;    FD_ZERO(&wset);    FD_ZERO(&rset);    FD_SET(sockClient, &wset);    FD_SET(sockClient, &rset);    int time1 = time (NULL);    int n = select(sockClient + 1, &rset, &wset, NULL, & tm );    int time2 = time (NULL);    printf ( "time gap is %d\n" , time2 - time1);    if (n < 0)    {     printf ( "select error, n is %d\n" , n);    }    else if (n == 0)    {     printf ( "connect time out\n" );    }    else if (n == 1)    {     if (FD_ISSET(sockClient, &wset))     {      printf ( "connect ok!\n" );      fcntl(sockClient, F_SETFL, fcntl(sockClient, F_GETFL, 0) & ~O_NONBLOCK);     }     else     {      printf ( "unknow error:%s\n" , strerror ( errno ));     }    }    else    {    printf ( "oh, not care now, n is %d\n" , n);    }   }   }   printf ( "I am here!\n" );    getchar ();    close(sockClient);    return 0; }

服务端代码,我们已经写过多次,本文就不写了。

经测试,上述程序OK, 用tcpdump抓包,还能学到不少东西,比如SYN包重传,RST包等。有点意思。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/stpeace/article/details/75175157

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容