Originally Posted by
pobri19
Hey, thanks a lot for suggesting this. This is exactly what I was after but didn't think of it until you mentioned it
Cheers.
That's not a good way to handle a non-blocking connect. How long do you set the timer for? 10 seconds? So if it takes 1 second, does your application wait another 9 seconds before it realizes the connect succeeded? You don't want that, so maybe make your timer go off every second and check if the connect succeeded. Now you are basically polling the socket. If that's the case, why have a timer at all? You could just make a while loop that sleeps for a second, then checks the socket.
Or you could just use the method that all the other programmers use which is the select() call.
I modified your code a little bit, and guess what... it works just fine.
Code:
int Host_Alive() {
WSAData data;
WSAStartup( MAKEWORD(2,2), &data);
sockaddr_in serv;
SOCKET sockfd;
serv.sin_addr.S_un.S_addr = inet_addr("209.85.171.100"); // google's IP
serv.sin_family = AF_INET;
serv.sin_port = htons(80);
sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
unsigned long iMode = 0;
ioctlsocket(sockfd, FIONBIO, &iMode); // put socket in non-blocking state
int ret = connect(sockfd, (struct sockaddr*)&serv, sizeof(serv));
if(ret == -1 && WSAGetLastError() != WSAEWOULDBLOCK)
{
printf("Error, connect() failed [%d]\n", WSAGetLastError());
closesocket(sockfd);
return 0;
}
fd_set socket_set;
timeval timer;
FD_ZERO(&socket_set);
FD_SET(sockfd, &socket_set);
timer.tv_sec = 5;
timer.tv_usec = 0;
printf("About to select\n");
ret = select(0, NULL, &socket_set, NULL, &timer);
printf("Select returned %d\n", ret);
if (!ret || ret == SOCKET_ERROR) {
printf("host not alive\n");
closesocket(sockfd);
return 0;
}
else
printf("[!] Host up!\n");
closesocket(sockfd);
return 1;
}