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