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

前端 未结 3 1808
梦毁少年i
梦毁少年i 2021-02-05 08:18

I am developing a RTSP Source filter in C++, and I am using WINSOCK 2.0 - blocking socket.

When I create a blocking socket, I set its SO_RCVTIMEO to 3 secs l

3条回答
  •  长情又很酷
    2021-02-05 08:59

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

提交回复
热议问题