WINSOCK - Setting a timeout for a connection attempt on a non existing IP?

自作多情 提交于 2019-12-03 01:50:31
Martin James

Bite the bullet. The remote IP may not be running a PING server or PING may be blocked by some router, so it's no help. Can you not just wait the 10 sec and then make whatever error indication you use?

If you absolutely have to time out the attempted connection after 3 seconds, you can time it out yourself.

Actually, Berkeley sockets have not timeout for connect, so you can not set it. ICMP PING is not helpful, i don't know why, but if host not exists you spend around 1 second with PING. Try use ARP for detect is host exists.

from cmd you can ping the ip with a timeout like this 'ping -w 100 -n 1 192.168.1.1'

it will return within 100mS

you can check the return code by 'echo %errorlevel% 0 = ok, 1 = fail, then you know if you should try connect

in c++

bool pingip_nowait(const char* ipaddr)
{
    DWORD exitCode;

    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );
    si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
    si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
    si.hStdOutput =  GetStdHandle(STD_OUTPUT_HANDLE);
    si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
    si.wShowWindow = SW_HIDE;

    CString cmd = "ping -w 100 -n 1 ";
    cmd += ipaddr;
    if (!CreateProcess(NULL,
        cmd.GetBuffer(),
        NULL,
        NULL,
        FALSE,
        0,
        NULL,
        NULL,
        &si,
        &pi)) {
            TRACE("ERROR: Cannot launch child process\n");
            return false;
    }

    // Give the process time to execute and finish
    WaitForSingleObject(pi.hProcess, 200L);

    if (GetExitCodeProcess(pi.hProcess, &exitCode))
    {
        TRACE("ping returned %d\n", exitCode);
        // Close process and thread handles. 
        CloseHandle( pi.hProcess );
        CloseHandle( pi.hThread );
        return exitCode==0 ? true : false;
    }
    TRACE("GetExitCodeProcess() failed\n");
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
    return false;
} 
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!