简体   繁体   中英

Java Socket: How to bind a specific local address to a Socket without a port number specified

I want to let the user have the freedom to choose a specific local address to connect to the target server since there might be customized routing policies, but want the program to pick up an ephemeral port instead of specifying one since that may need manual-test of local port availability.

I checked the constructors of "Socket" and "InetSocketAddress", it seems none of them have one to do the above task (even though it can pick up a local address and an ephemeral port simultaneously), and there is no method to do so after the initialization.

You can create a Socket and call connect on it later.

Socket socket = new Socket(); // no idea where to connect

socket.connect(addressAndPort); // now I know.

What I do is have a TCPRegistry for testing purposes. This component takes care of aliased ports. eg host.port1 . It gives it an ephemeral port on the server and allows the client to connect to it using the same string.

Note: to allow the client to start before the server I can ask it to pre-build these ServerSocket in the unit test.

Finally, at the end of the test, I can either check all Sockets and ServerSockets were closed, or forcefully clean them up.

It is designed for NIO, but could be adapted for plain IO TCPRegistry

There is a construtor

public Socket(InetAddress address,
  int port,
  InetAddress localAddr,
  int localPort)
   throws IOException

that should be suitable for your requirement. If localPort is 0, the system will pick a free port.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM