Q:

connect to one of many servers, with socket

i have a client that must connect to one of many servers, i have 5 server with port from 8000 to 8004, and one client that must connect to the first server that is online. my idea is to try to connect to each server until one connection is established, in this way:
definition of structure
char * host_name = "127.0.0.1"; // local host
int port[5] = {8000,8001,8002,8003,8004}

struct sockaddr_in serv_addr;
struct hostent* server;

if ( ( server = gethostbyname(host_name) ) == 0 )
{
    perror("Error resolving local host\n");
    exit(1);
}

int sockfd = socket( PF_INET, SOCK_STREAM, 0 );
if ( sockfd == -1 )
{
    perror("Error opening socket\n");
    exit(1);
}

This is what i do for resolving the issue
bzero(&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = ((struct in_addr *)(server->h_addr))->s_addr;

for (int i=0;i<5;i++){
    serv_addr.sin_port = htons(port[i]);
    if ( connect(sockfd, (void*)&serv_addr, sizeof(serv_addr) ) != -1 )
    {
        printf("connect to server %d\n",port[i]);
        break;
    } else{
        printf("impossible to  connect to server %d \n",port[i]);
    }
}

This work only if the first server (port 8000) is online, the connection is established.
If the server with port from 8001 to 8004 are online the connection is not established.
Of course in the server side there is a listen() on a new connection.

A:

You can't reconnect a socket that has already tried to connect, even if it failed. You have to close it and create a new socket.

