在linux下玩转带有超时时间的connect函数
在之前的文章中,我们在Windows下玩过带有超时时间的,本文我们在linux下来玩。在某次面试中,还被遇到了这个问题,有意思。
直接上客户端代码:
#include#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include intmain(intargc,char*argv[])//注意输入参数,带上ip和port { intsockClient=socket(AF_INET,SOCK_STREAM,0); structsockaddr_inaddrSrv; 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); intiRet=connect(sockClient,(conststructsockaddr*)&addrSrv,sizeof(structsockaddr_in)); printf("connectiRetis%d,errmsg:%s\n",iRet,strerror(errno));//返回-1不一定是异常 if(iRet!=0) { if(errno!=EINPROGRESS) { printf("connecterror:%s\n",strerror(errno)); } else { structtimevaltm={5,0}; fd_setwset,rset; FD_ZERO(&wset); FD_ZERO(&rset); FD_SET(sockClient,&wset); FD_SET(sockClient,&rset); inttime1=time(NULL); intn=select(sockClient+1,&rset,&wset,NULL,&tm); inttime2=time(NULL); printf("timegapis%d\n",time2-time1); if(n<0) { printf("selecterror,nis%d\n",n); } elseif(n==0) { printf("connecttimeout\n"); } elseif(n==1) { if(FD_ISSET(sockClient,&wset)) { printf("connectok!\n"); fcntl(sockClient,F_SETFL,fcntl(sockClient,F_GETFL,0)&~O_NONBLOCK); } else { printf("unknowerror:%s\n",strerror(errno)); } } else { printf("oh,notcarenow,nis%d\n",n); } } } printf("Iamhere!\n"); getchar(); close(sockClient); return0; }
服务端代码,我们已经写过多次,本文就不写了。
经测试,上述程序OK, 用tcpdump抓包,还能学到不少东西,比如SYN包重传,RST包等。有点意思。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对毛票票的支持。如果你想了解更多相关内容请查看下面相关链接
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。