Home > Software engineering >  How to implement socket connect() when the server is not running?
How to implement socket connect() when the server is not running?

Time:01-08

The following TCP/IP client code works as expected if the server is running before I call this function. If the server is not running, connect() returns immediately and prints errno = 111, connection refused. I ended up placing the call to connect() in an infinite while-loop with a 1-second delay between calls. When the server is up, the code connects and exits the loop. Q: Is this how connect() in blocking mode supposed to work? If so, is there a way to configure connect() to wait until the server is running before returning?

int socket_connect(const char *host, int port, int timeout)
{
    struct sockaddr_in sa;
    struct hostent *hp;
    int sockfd = -1;
    
    hp = gethostbyname(host);
    if (hp == NULL)
    {
        return -1;
    }
    
    sa.sin_family = AF_INET;
    sa.sin_port = htons(port);
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    int status = connect(sockfd, (struct sockaddr *)&sa, sizeof(sa));
    if (status != 0)
    {
        close(sockfd);
        printf("errno = %d\n",errno);
        return -2;
    }
    ...

CodePudding user response:

connect has a single task - establish a connection to a (remote) server socket. This server socket is expected to exist for this, i.e. the server application holding this socket is expected to be running. And the server system is expected to be reachable. connect is just doing internally the TCP handshake, i.e. it sends a SYN packet and wait for the SYN ACK for the server.

If the server application is running and listening on the server socket and if the server system is reachable (i.e. no connectivity loss or firewall blocking connection) then the server system will respond quickly with SYN ACK and connect will succeed in a short time.

If the server application is not running or not (yet) listening on the server socket, then the server system will explicitly reject the connection attempt - resulting in connect returning with "connection refused". This is also the case if there is a firewall explicitly rejecting the connection or if the server is running out of resources, like if the listen queue for the server socket is full.

If instead there is a loss of connectivity or if there is a firewall which will block connections attempts by simply dropping the packets before they reach the server system, then connect will internally try to reach the server by repeatedly retrying sending the SYN to get a response back. After a while connect will give up and consider the connection attempt failed with "timed out".

  • Related