The only thing I see right away is that your timeout value is pretty short. Half a second... Factor in the accuracy of clock ticks and it often could be much shorter. For what it's worth, here's an alternative method using an event instead of looping (which is inefficient use of CPU!)...
tmpSocket = ::socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) ;
if (tmpSocket != INVALID_SOCKET)
{
BOOL fConnectSuccess = FALSE;
HANDLE hNetEvent = ::CreateEvent(NULL, true, false, NULL); // manual reset
::WSAEventSelect(tmpSocket, hNetEvent, FD_CONNECT);
// Socket is now NON-blocking
sockaddr_in SClient;
SClient.sin_family = AF_INET;
SClient.sin_port = htons(502);
SClient.sin_addr.s_addr = inet_addr(strIPAddr);
// Attempt to Connect - timeout 10 seconds
if (SOCKET_ERROR == ::connect(tmpSocket, (sockaddr *) &SClient, sizeof(sockaddr_in)))
{
int rc = WSAGetLastError();
if (rc == WSAEWOULDBLOCK)
{
if (WAIT_OBJECT_0 == ::WaitForSingleObject(hNetEvent, 10000))
{
WSANETWORKEVENTS WsaNetworkEvents;
if (0 == ::WSAEnumNetworkEvents(tmpSocket, hNetEvent, &WsaNetworkEvents)) //(resets hNetEvent)
{
if (0 != WsaNetworkEvents.iErrorCode[FD_CONNECT_BIT])
{
// connect error occurred
}
else
{
// connect success!
fConnectSuccess = TRUE;
}
}
}
else
{
// timed out
}
}
else
{
//::connect() failed
}
}
else
{
// connect success!
fConnectSuccess = TRUE;
}
::closesocket(tmpSocket);
::CloseHandle(hNetEvent);
return fConnectSuccess;
}
else
{
return FALSE;
}
-- modified at 13:42 Wednesday 23rd May, 2007 added cleanup for event handle :rolleyes:
"Posting a VB.NET question in the C++ forum will end in tears." Chris Maunder