-1

I am developing a peer-to-peer application in Rust and my goal is to only have one TCP connection (1 TcpStream) where to read from and write to. This is the example network shape:

Network architecture

It is important that every connection from a node to the others is from the same IP address and port. I am trying to implement a preliminary step to create all the connections and store them, to later both listen and write on them.

I have tried the following using the std::net::TcpStream and std::net::TcpListen:

  1. Every node starts and listens for connections on their address (1.1.) and then connects to the others (1.2.). Result: all the nodes get block listening and none of them advances.

  2. Every node listens for a connection from all the nodes with a lower index (2.1.) and creates a connection using TcpStream::connect for all the nodes with a greater index (2.2.), in separate threads. Result: The desired connection is established, but the connection created TcpStream::connect are from a random port.

  3. The same as 2., but create the connection (in 2.2.) using socket2 library that allows to bind an address before connecting. Result: I obtain an error saying "Transport endpoint is already connected" after the second try to bind the socket.

Is this possible? In that case, how should I implement it?

I want to note that I plan on implementing a poll using mio from all the sockets. Maybe this is an impediment to create the collection of sockets and read and write at the same time.

Please ask for any clarification if needed.

javier
  • 113
  • 9
  • 1
    It is usually bad practice to require a fixed port from the TCP client (the one that calls connect). What is the reason behind this requirement? – kmkaplan Sep 25 '22 at 16:15
  • @kmkaplan In my application, each node knows the others by an IP pre-assigned at the beginning. This IP will be used by the nodes to send messages to the others, but I want to know which of these nodes has sent me a message (reading the IP and comparing it to the pre-assigned ones). – javier Sep 25 '22 at 16:23
  • that doesn't answer why the *port* has to be fixed – kmdreko Sep 25 '22 at 16:27
  • You are right, @kmkaplan, the port also has to be the same because they are pre assigned too – javier Sep 25 '22 at 16:27

1 Answers1

0

You can call socket.set_reuse_port(true) and socket.set_reuse_address(true) before calling socket.bind(address) to make your connection succeed.

See https://stackoverflow.com/a/14388707/50902 for the details of what each of these calls do.

kmkaplan
  • 18,655
  • 4
  • 51
  • 65