Skip to content

Commit

Permalink
Bind to IPv4 Loopback Address
Browse files Browse the repository at this point in the history
  • Loading branch information
dfuchss committed Jul 12, 2024
1 parent 068cde8 commit a238571
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions cli/src/main/java/de/jplag/cli/server/ReportViewer.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.BindException;
import java.net.InetAddress;
import java.net.InetSocketAddress;

import org.apache.commons.lang3.ArrayUtils;
Expand All @@ -27,7 +28,6 @@ public class ReportViewer implements HttpHandler {
private static final int SUCCESS_RESPONSE = 200;
private static final int NOT_FOUND_RESPONSE = 404;
private static final int MAX_PORT_LOOKUPS = 4;
private static final String DEFAULT_IP_ADDRESS = "0.0.0.0";

private final RoutingTree routingTree;
private final int port;
Expand Down Expand Up @@ -59,12 +59,14 @@ public int start() throws IOException {
throw new IllegalStateException("Server already started");
}

System.setProperty("java.net.preferIPv4Stack", "true");

int currentPort = this.port;
int remainingLookups = MAX_PORT_LOOKUPS;
BindException lastException = new BindException("Could not create server. Probably due to no free port found.");
while (server == null && remainingLookups-- > 0) {
try {
server = HttpServer.create(new InetSocketAddress(DEFAULT_IP_ADDRESS, currentPort), 0);
server = HttpServer.create(new InetSocketAddress(InetAddress.getByAddress(new byte[] {127, 0, 0, 1}), currentPort), 0);
} catch (BindException e) {
logger.info("Port {} is not available. Trying to find a different one.", currentPort);
lastException = e;
Expand Down

0 comments on commit a238571

Please sign in to comment.