Home > Mobile >  how to reconnect client to different server ip in C without opening new socket
how to reconnect client to different server ip in C without opening new socket

Time:06-14

Is it possible to close an old server ip connection and connect it to a new server ip in a client side socket program using C? I have my client program connected with server over SCTP connection and at certain condition I want to disconnect from an old server and connect to new one without opening a new socket? Client side code:

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);
}


if(due_to_some_condition_got_new_server_ip){
        ------------------------------> I have new server_ip2 to connect 
}

CodePudding user response:

It's not possible.

Open a new socket.

Even if it was possible, it wouldn't be faster than opening a new socket. The slow part of connecting a socket is that your computer has to send a packet to the other computer and get a reply back. That happens no matter whether you connect the same socket or a different one.

CodePudding user response:

With a 1-to-1 style interface (using SOCK_STREAM, as you are), it is not possible to reuse a socket, no. The socket is associated with only 1 connection, and that connection cannot be changed. To connect to a new server IP, you must close the old socket and connect() a new socket.

With a 1-to-many style interface (using SOCK_SEQPACKET), it is possible to reuse the socket, as you would not be using connect() at all, just sendmsg() and recvmsg(). So you would just sendmsg() to the desired server IP on a per-message basis. You can use setsockopt() to enable the SCTP_AUTOCLOSE option to close idle connections that you are not using anymore.

Read the man documentation for more details: https://linux.die.net/man/7/sctp

  • Related