-1

I've a small agent that supposed to connect to server from time to time first stage it opens a socket:

const char* hostname // e.g. "127.0.0.1"   
hostaddr = inet_addr(hostname);

    /* Ultra basic "connect to port 22 on localhost"
     * Your code is responsible for creating the socket establishing the
     * connection
     */ 
    sock = socket(AF_INET, SOCK_STREAM, 0);

    sin.sin_family = AF_INET;
    sin.sin_port = htons(22);
    sin.sin_addr.s_addr = hostaddr;
    if (connect(sock, (struct sockaddr*)(&sin),
                sizeof(struct sockaddr_in)) != 0) {
        fprintf(stderr, "failed to connect!\n");
        return -1;
    }

when ip-address is not valid it seems that connect hangs for very long time before failing

looking at the man page provide some data on the subject but not how to overpass it

My question is why and how can I add timeout for it (or any other solution)

LordTitiKaka
  • 2,087
  • 2
  • 31
  • 51

1 Answers1

0

Quoted from one of the answers here

Put the socket into non-blocking mode until you've connected, and then put it back into blocking mode once the connection's established.

Nyque
  • 351
  • 3
  • 10
  • 1
    The correct thing to do was to mark this question as a duplicate of another qurstion, not quote an answer from that other question. You didn't even quote the best answer, as several of the other answers explained how to implement the timeout, but the one you quoted does not. – Remy Lebeau Jun 23 '18 at 17:03