socket connect 函数设置超时

使用Winsock connect函数,无法设置超时,而在连接一个不存在的主机时,将会阻塞至少要几十秒。其实在调用connect函数时,将socket设置为非阻塞,然后调用select函数,可以达到设置超时的效果。

bool ConnectWithTimeout(SOCKET socket, char * host, int port, int timeout)
{
    TIMEVAL timeval = {0};
    timeval.tv_sec = timeout;
    timeval.tv_usec = 0;
    struct sockaddr_in address;  

    address.sin_family = AF_INET;
    address.sin_port = htons(port);
    address.sin_addr.s_addr = inet_addr(host);
    if(address.sin_addr.s_addr == INADDR_NONE)
        return false;

    // set the socket in non-blocking
    unsigned long mode = 1;
    int result = ioctlsocket(socket, FIONBIO, &mode);
    if (result != NO_ERROR) 
        printf("ioctlsocket failed with error: %ld\n", result);

    connect(socket, (struct sockaddr *)&address, sizeof(address));

    // restart the socket mode
    mode = 0;
    result = ioctlsocket(socket, FIONBIO, &mode);
    if (result != NO_ERROR)
        printf("ioctlsocket failed with error: %ld\n", result);

    fd_set Write, Err;
    FD_ZERO(&Write);
    FD_ZERO(&Err);
    FD_SET(socket, &Write);
    FD_SET(socket, &Err);

    // check if the socket is ready
    select(0, NULL, &Write, &Err, &timeval);
    if(FD_ISSET(socket, &Write))
        return true;

    return false;
}

 

posted on 2012-12-26 12:39  zhuyf87  阅读(10081)  评论(0编辑  收藏  举报

导航