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));
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:
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.
The second solution is to use threads. Then the connection attempt can work in the background while your main thread does something else.