Skip to content

Commit

Permalink
[#29] Fix Failing Test due to Unwanted Port Reuse
Browse files Browse the repository at this point in the history
It looks like this test was failing because the kernel is reusing the same port for two different sockets within the same application (despite us not asking for this at all). In JDK 9+, we can control this via `StandardSocketOptions.SO_REUSEPORT`, but that option is not available in JDK 8. As a workaround, setting address reuse on the placeholder socket seems to prevent the subsequent socket from binding to the same port.
  • Loading branch information
Kortanul committed Apr 18, 2019
1 parent 3a60e66 commit 9e5a6fa
Showing 1 changed file with 18 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
*
*
* Copyright 2014 ForgeRock AS.
* Portions Copyright 2019 Wren Security.
*/
package org.forgerock.opendj.server.setup.model;

Expand Down Expand Up @@ -72,13 +73,23 @@ public void testGetDefault() {
public void testGetFreePort() throws Exception {
// Finds a free socket
final InetSocketAddress isa = TestCaseUtils.findFreeSocketAddress();
// Bound the free socket
final int port = isa.getPort();
final ServerSocket boundSocket = new ServerSocket(port);
// Verify the new port number is different from the free socket and verify it's free.
final int newPort = ListenerSettings.getFreeSocketPort(port);
assertThat(newPort).isNotEqualTo(port);
assertTrue(Math.abs(newPort - port) % PORT_INCREMENT == 0);

// Bind the free socket
final int boundPort = isa.getPort();
final ServerSocket boundSocket = new ServerSocket();

// NOTE: This seems to work for JDK 8+; but, in JDK 9+, the next code line should switch to
// being the following instead (which is more precise):
//
// boundSocket.setOption(StandardSocketOptions.SO_REUSEPORT, false);
//
boundSocket.setReuseAddress(false);
boundSocket.bind(new InetSocketAddress(boundPort));

// Verify the new port number is different from the bound socket and verify it's free.
final int newPort = ListenerSettings.getFreeSocketPort(boundPort);
assertThat(newPort).isNotEqualTo(boundPort);
assertTrue(Math.abs(newPort - boundPort) % PORT_INCREMENT == 0);

boundSocket.close();
}
Expand Down

0 comments on commit 9e5a6fa

Please sign in to comment.