当前位置: 移动技术网 > 网络运营>服务器>Linux > 在linux下玩转带有超时时间的connect函数

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

2019年07月18日  | 移动技术网网络运营  | 我要评论
在之前的文章中,我们在windows下玩过带有超时时间的,本文我们在linux下来玩。在某次面试中,还被遇到了这个问题,有意思。 直接上客户端代码: #incl

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

直接上客户端代码:

#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包等。有点意思。

总结

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

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网