0
votes

I need help about setting 3 UDP socket. Sockets are the same a part of the remote port number that must be 61000,61001 and 61002. I need set this socket because I should use them on select function, to send and receive data.

I tried a lot of methods, but no one worked properly. I know that this is the normal procedure to set ONE socket:

int set_socket() {

  /* get a datagram socket */
  sock = socket(AF_INET, SOCK_DGRAM, 0);
  if (sock == SOCKET_ERROR) {
    printf ("socket() failed, Err: %d \"%s\"\n", errno,strerror(errno));
    exit(1); 
  } 
  OptVal = 1;
  ris = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&OptVal, sizeof(OptVal));
    if (ris == SOCKET_ERROR)  {
      printf ("setsockopt() SO_REUSEADDR failed, Err: %d \"%s\"\n", errno,strerror(errno));
      exit(1);
    }
  /* name the socket */
  Local.sin_family      =   AF_INET;
  Local.sin_addr.s_addr =   htonl(INADDR_ANY);
  Local.sin_port        =   htons(local_port_number_UDP);
  ris = bind(sock, (struct sockaddr*) &Local, sizeof(Local));
  if (ris == SOCKET_ERROR)  {
    printf ("bind() failed, Err: %d \\n",errno);
    exit(1);
  }
  /* assign our destination address */
  To.sin_family               = AF_INET;
  To.sin_addr.s_addr          = inet_addr(string_remote_ip_address_UDP);
  To.sin_port                 = htons(remote_port_number_UDP);

}

How I can set all 3 socket with a different remote port number? I must use different struct (Local and To) for each socket?

Thanks, and sorry for my bad English.

1
using 3 sockets seems kind of wasteful. most apps use a SINGLE socket and simply put some identifying data into the packet to say what's happening. e.g. "this is an update packet, and here's the data". "this is a get packet, and here's the request".Marc B
That's not the last reason why protocals have been invented...Abu Dun
so what i need if I should send and receive from 3 different port?Alessandro Mercurio

1 Answers

0
votes

I must use different struct (Local and To) for each socket?

No, you can reuse the same Local (after changing sin_port) for the bind of the two other sockets. You can reuse the same To if you change sin_port each time you need it for another socket.