'programming/C_C++'에 해당되는 글 279건

  1. 2010.09.10 connect_nonb

connect_nonb

programming/C_C++ 2010. 9. 10. 11:30
반응형


URL:http://kldp.org/node/91616

 

int connect_nonb(int sockfd, const struct sockaddr *saptr, socklen_t salen, int nsec)
{
 int    flags, status, error;
 socklen_t  len;
 fd_set    rset, wset;
 struct timeval tval;
 int fd_max;
 
 flags = fcntl(sockfd, F_GETFL, 0);
 
 if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) < 0)
 {
  printf("[Error] Non block mode set fail !\n");
  return -1;
 }
 
 error = 0;
 
 printf("[INFO] connect function load\n");

 status = connect(sockfd, (struct sockaddr *)saptr, salen);
 
 if ((status < 0) && (error == EINPROGRESS))
 {
  printf("[INFO] connection fail !!\n");
  return(-1);
 }
 
 /* Do whatever we want while the connect is taking place. */
 
 if (status == 0)
  goto done; /* connect completed immediately */
 
 FD_ZERO (&rset);
 FD_SET (sockfd, &rset);
 wset = rset;
 
 tval.tv_sec = nsec;
 tval.tv_usec = 0;
 
 printf("[INFO] select function load\n");

 if ((status = select(sockfd + 1, &rset, &wset, NULL, nsec ? & tval : NULL)) == 0) {
  printf("[INFO] select return time out\n");
  close(sockfd);
  error = ETIMEDOUT;
  return (-1);
 }
 
 if (FD_ISSET(sockfd, &rset) || FD_ISSET(sockfd, &wset)) {
  len = sizeof(error);
  if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)
   return (-1);
 } else {
  printf("[Error] select error: sockfd not set\n");
  return (-1);
 }
 
 
 
done:

 fcntl(sockfd, F_SETFL, flags); /* restore file status flags */
 
 if (error) {
  printf("[Error] socket error\n");
  close(sockfd);  /* just in case */
  return(-1);
 }
 printf("[Info] nonb connection complete !! \n");
 return(0);
}



 

반응형
Posted by 공간사랑
,