connect timeout

转自点击打开链接http://www.cnblogs.com/zhuyf87/archive/2012/12/26/2833832.html

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值