| [ CnUnix ] in KIDS 글 쓴 이(By): guest (talkhard) <203.255.254.154> 날 짜 (Date): 2003년 2월 19일 수요일 오후 12시 58분 03초 제 목(Title): Re: [Q] socket에서 connect() 잠깐 소스 코드를 보여드리면... 다른 소스코드의 일부라 그냥 참고만 하시길... // if the socket was blocking socket and timeout // argument indicates that the nonblocking operation is // needed, temporarily convert this socket as nonblocking socket. if ( _block && timeout >= 0 ) { if ( (flags = fcntl(_sock_d, F_GETFL, 0)) < 0 ) { ret = -1; goto done; } // set this as nonblock socket fcntl(_sock_d, F_SETFL, flags | O_NONBLOCK); } sockaddr_in servaddr; sethostinfo(&servaddr, hostname, port); if ( (n = ::connect(_sock_d, (sockaddr*)&servaddr, sizeof(servaddr)))<0 ) { if ( errno != EINPROGRESS ) { ret = -1; goto done; } } if ( n != 0 ) { // connection is not completed immediately. so, start select fd_set rset, wset; timeval tval; FD_ZERO(&wset); FD_SET(_sock_d, &wset); rset = wset; tval.tv_sec = timeout; tval.tv_usec = 0; n = select(_sock_d+1, &rset, &wset, NULL, (timeout<0)?NULL:&tval); // timeout happend if ( n == 0 ) { ret = -1; } // something has arrved else { if ( FD_ISSET(_sock_d, &wset) || FD_ISSET(_sock_d, &rset) ) { int err; socklen_t l = sizeof(err); if ( ::getsockopt(_sock_d,SOL_SOCKET,SO_ERROR,&err,&l)<0 ) { ret = -1; } else { if ( err == 0 ) { ret = 1; } else { ret = -1; } } } else { ret = -1; // connection failed } } } else { // connection is successfuly established ret = 1; } done : // restore socket properties to that of blocking socket. if ( _block && timeout >= 0 ) { if ( fcntl(_sock_d, F_SETFL, flags) < 0 ) { ret = -1; } } |