0

I am writing a C client server program using SCTP, so that at begin there is only one socket opened on client side for send and recv which is used by all threads. After a certain condition I have to open a new socket, now I have two of them and at this point both socket should be used for sending and receiving on a round-robin (alternate) fashion by all threads for load sharing. Similarly, as the no of sockets increase, it should be used by client alternative for load sharing. is there a suggestion to achieve this? Using select, poll, normal sockets etc?

connSock = socket (AF_INET, SOCK_STREAM, IPPROTO_SCTP);
if (connSock == -1)
{
      perror("socket()");
      exit(1);
}

struct sctp_paddrparams params;
len = sizeof(params);

memset(&params, 0, sizeof(params));
if (getsockopt(connSock, IPPROTO_SCTP, SCTP_PEER_ADDR_PARAMS, &params, &len)) {
       perror("getsockopt");
       exit(1);
}
        
// set client address
struct sockaddr_in localaddr;
localaddr.sin_family = AF_INET;
char* client_ip = get_our_ip();
localaddr.sin_addr.s_addr = inet_addr(client_ip) ;
localaddr.sin_port = 0; 
bind(connSock, (struct sockaddr *)&localaddr, sizeof(localaddr));

// set server address
bzero ((void *) &servaddr, sizeof (servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons (port); 
servaddr.sin_addr.s_addr = inet_addr(server_ip); 

ret = connect(connSock, (struct sockaddr *) &servaddr, sizeof (servaddr)); 
if (ret == -1)
{
    perror("connect()");
    close(connSock);
    exit(1);
}

// ----> at this point only one socket is opened from client and all threads are using the same.

if(due_to_some_condition_got_new_server_ip){
// --> I have opened a new socket to connect to server_ip2. Now we 
// have 2 sockets opened, hence all threads should use sockets alternatively to send and receive data 

}
myquest4 sh
  • 371
  • 4
  • 16
  • The only way something like that makes any sense is multiple server processes/threads each listening for connections. Either each with a different socket bound to a different port (possibly behind a load balancer), or all accepting on the same socket. This is an old, old problem for high traffic httpd servers; you can look at how they address it. – Shawn Jun 15 '22 at 09:59
  • you have an array of sockets, you remember which one was the last one you used, and every time you send something, you send it to the next socket in the array – user253751 Jun 15 '22 at 10:31

0 Answers0