Reputation: 1236
This link provides a tutorial for opening a non-blocking socket. However the method provided here doesn't gives option of picking up any random port. Also all the constructors shown at this java doc page takes address as argument. Any way to do this?
Upvotes: 3
Views: 1753
Reputation: 804
If you look at the constructors for InetSocketAddress, it is stated that
A valid port value is between 0 and 65535. A port number of zero will let the system pick up an ephemeral port in a bind operation.
In essence, just pass in an InetSocketAddress
, using 0 for the port argument, and this will result in a random port being chosen.
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
// Use wildcard ip (*) and ephemeral port
serverSocketChannel.socket().bind(new InetSocketAddress(0));
Upvotes: 8
Reputation: 546
Its bit hacky solution but has worked for me. You can create a normal Socket, with port argument as 0(so you get an random available socket) connect on it, then grab its address. Now close this socket and pass this address as argument while creating SocketChannel. However be cautious this may be a trouble in multi-threaded program where threads are creating socket in parallel. Consider two parallel threads t1 and t2. Suppose t1 created a socket grabbed its address, closed it and then got context switched. Now t2 got the same port, before t1 was able to connect on a Non-blocking channel, using this socket. For such case it would be good to keep looping till the non-blocking (SocketChannel) connection is not established.
Upvotes: 3