socket connect 函式設定超時

weixin_34391854發表於2012-12-26

使用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;
}

 

相關文章