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

  1. 2011.05.19 connect timeout

connect timeout

programming/C_C++ 2011. 5. 19. 11:46
반응형

connect timeout


int  error = 0;
fd_set   rset;
fd_set   wset;
int  n;
const SOCKET sock = m_Socket;

// set the socket as nonblocking IO
const int flags = fcntl (sock, F_GETFL, 0);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);

errno = 0;

// we connect, but it will return soon
n = ::connect(sock, addr, size_addr);

if(n < 0) {
    if (errno != EINPROGRESS) {
        return -1;
    }
} else if (n == 0) {
    goto done;
}

FD_ZERO(&rset);
FD_ZERO(&wset);
FD_SET(sock, &rset);
FD_SET(sock, &wset);

struct timeval tval;
tval.tv_sec = timeout;
tval.tv_usec = 0;

// We "select()" until connect() returns its result or timeout
n = select(sock + 1, &rset, &wset, 0, timeout ? &tval : 0);
if(n == 0) {
    errno = ETIMEDOUT;
    return -1;
}

if (FD_ISSET(sock, &rset) || FD_ISSET(sock, &wset)) {
    socklen_t len = sizeof(error);
    if (getsockopt(SOL_SOCKET, SO_ERROR, &error, &len) < 0) {
    return -1;
    }
} else {
    return -1;
}

done:
// We change the socket options back to blocking IO
if (fcntl(sock, F_SETFL, flags) == -1) {
    return -1;
}
return 0;


http://ko.w3support.net/index.php?db=so&id=735249


 

반응형
Posted by 공간사랑
,