Voxito
Voxito

Reputation: 33

Listening with 2 sockets on server

I've created a server that listens on 1 socket that works fine, and now I need to add another socket.

I've read some questions/answers here about how to create it, but so far without any success.

I'm running both clients and server on my local laptop, and as I'm trying to bind the second socket, I'm getting the follow error: bind: Address already in use while running the server, in the terminal.

Can anyone give me maybe a little hint about what I'm doing wrong and how can I create 2 sockets to listen on the same address?

  int s, s2, len, b, b2, blen;
  struct sockaddr_un local, remote, blocal;
  socklen_t t, bt;
  if ((b = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
     perror("socket");
      exit(1);
    }
  if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(1);
  }

  blocal.sun_family = AF_UNIX;
  strcpy(blocal.sun_path,SOCK_PATH);
  unlink(blocal.sun_path);
  local.sun_family = AF_UNIX;
  strcpy(local.sun_path, SOCK_PATH);
  unlink(local.sun_path);

  len = strlen(local.sun_path) + sizeof(local.sun_family);
  blen = strlen(blocal.sun_path) + sizeof(blocal.sun_family);
  if (bind(s, (struct sockaddr * ) & local, len) == -1) {
    perror("bind");
    exit(1);
  }

 if (bind(b, (struct sockaddr * ) & blocal, blen) == -1) {
    perror("bind");
    exit(1);
  }  

I've cut the rest of the code where it gets to listen etc since that's where I get the error.

Upvotes: 0

Views: 331

Answers (1)

kakurala
kakurala

Reputation: 824

Two sockets cannot listen on same port number, you need to create two sockets binding to different ports and then have a load balancer in front of them to share the load across.

Or, if you want to create one socket but the requests should be handled by multiple threads or processes then you can utilize shared memory concept (usually in C or C++). So when request comes in then the server socket process can copy the request content to shared memory and then the child processes or threads can pick the request from it and then process further.

This model is being used by apache HTTP server.

Upvotes: 1

Related Questions