Monday, August 13, 2012

Non Blocking Connect with Timeout

Connect is blocking
 If there is no response  retries will be done on interval which keeps increasing for minutes .
If we need to return quicker connect should be done as nonblocking and time can be set for how long wait for SYN ACK from Server.


fd_set fdset;
struct timeval tv;
int flags ;
  //NON blocking
    if ((flags = fcntl(sock, F_GETFL))<0 br="br">    {
       printf("fcntl get FL failed\n");
       return -1;
    }
    if( fcntl(sock, F_SETFL, O_NONBLOCK)<0 br="br">    {   printf("fcntl get FL failed\n");
       return -1;
    }
 if (connect(sock, (struct sockaddr *) &echoServAddr, sizeof(echoServAddr)) < 0)
        {

          if (errno != EINPROGRESS)
           {
             perror("connect() failed");
             exit(0);
           }
        }
        printf("non blockinng connect() passed \n");

  FD_ZERO(&fdset);
  FD_SET(sock, &fdset);
  tv.tv_sec = 3;
  tv.tv_usec = 0;

   if (select(sock + 1, NULL, &fdset, NULL, &tv) == 1)
   {
      int so_error;
      socklen_t len = sizeof so_error;
      getsockopt(sock, SOL_SOCKET, SO_ERROR, &so_error, &len);
      if (so_error == 0)
      {
         printf("  CONNECTION ESTABLISHED\n");
         fflush(NULL);
      }
      else
      {
          printf("  CONNECTION FAILED\n");
           return-1;
      }
   }
   else
   {
      printf(" CONNECTION  TIMEOUT\n");
      fflush(NULL);
      return-1;
   }

No comments:

Post a Comment