Hi, I'm trying to write a function to check if a host is alive in a given specific time frame. For example, say I wanted to give this function 5 seconds to check if the host is alive, if a connection cannot be established properly within 5 seconds then I presume the host is down and return 1, otherwise I return 0.
For some reason this function ALWAYS returns 0 even if the host is not alive (aka it thinks the host is alive for some reason...) and the variable 'ret' is always equal to 1.
I'm trying to use a non-blocking socket, then a call to connect and then a call to select with that specific time limit to check if the host is up. I cannot seem to get it working.
Thanks!Code:// checks whether host is alive with a non-blocking socket and call to select on minimal timeout int Host_Alive(arguments * args) { args->serv.sin_addr.S_un.S_addr = inet_addr(args->sz_address); args->serv.sin_family = AF_INET; args->serv.sin_port = htons(args->port); args->sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); args->sz_address = new char[16]; strcpy(args->sz_address, inet_ntoa((in_addr)args->serv.sin_addr)); unsigned long iMode = 0; ioctlsocket(args->sockfd, FIONBIO, &iMode); // put socket in non-blocking state connect(args->sockfd, (const sockaddr *)&args->serv, sizeof(args->serv)); fd_set socket_set; timeval timer; socket_set.fd_array[0] = args->sockfd; socket_set.fd_count = 1; timer.tv_sec = args->timeout; int ret = select(0, &socket_set, &socket_set, &socket_set, &timer); if (!ret || ret == SOCKET_ERROR) { printf(" [!] Host %s:%d not alive: %d!\n", args->sz_address, args->port, ret); free(args); closesocket(args->sockfd); return 0; } else printf(" [!] Host up: %d!\n", ret); free(args); closesocket(args->sockfd); return 1; }



LinkBack URL
About LinkBacks




Cheers.