NJMR NJMR - 23 days ago 8
C Question

Call to Connect takes too much time

My task is to check wheter an IP is alive or not. So I followed this link and modified the code as shown below...

int isServerAlive(const char* serverAdd)
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);

struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(65432); // Could be anything.
inet_pton(AF_INET, serverAdd, &sin.sin_addr);

if (connect(sockfd, (struct sockaddr *) &sin, sizeof(sin)) == -1)
{
// The two main errors you get if the host is dead are ENETUNREACH and ETIMEDOUT.
if (errno == ENETUNREACH || errno == ETIMEDOUT)
{
printf("Error connecting %s: %d (%s)\n",serverAdd, errno, strerror(errno));
return FAILURE;
}
}
return SUCCESS;
}


When I try to execute this code, connect call is taking too much time.


  • Am I doing anything wrong here?

  • Are there any other better ways to check if an IP is alive or not?



Thanks in advance.

Answer

If the connection attempt times out, then the network stack will try again a few times. Waiting for a time out, and the retries unfortunately takes time.

There are basically two ways to solve it:

  1. Use non-blocking sockets. Then the connect call either returns with a valid connection. It it will return with an error and errno set to EINPROGRESS. As said in the connect manual page you can use e.g. select to see if the socket is writeable to know the connection attempt is finished, and you can get the status.

  2. The second solution is to use threads. Then the connection attempt can work in the background while your main thread does something else.