Skip to content

Commit

Permalink
Added a timeout on finding an available port.
Browse files Browse the repository at this point in the history
Signed-off-by: AntonJansen <gradius@fmf.nl>
  • Loading branch information
AntonJansen committed Oct 14, 2024
1 parent 9194d0e commit c3d7819
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,11 @@
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeoutException;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.broadlink.internal.handler.BroadlinkHostNotReachableException;
import org.openhab.core.net.NetUtil;
import org.slf4j.Logger;

/**
* Utilities for working with the local network.
Expand Down Expand Up @@ -84,14 +83,22 @@ public static InetAddress getLocalHostLANAddress() throws UnknownHostException {
* @param from port number of the start of the range
* @param to port number of the end of the range
* @return number of the available port
* @throws TimeoutException when no available port can be found in 30 seconds
*/
public static int nextFreePort(InetAddress host, int from, int to) {
public static int nextFreePort(InetAddress host, int from, int to) throws TimeoutException {
if (to < from) {
throw new IllegalArgumentException("To value is smaller than from value.");
}
int port = randInt(from, to);
long startTime = System.currentTimeMillis();
do {
if (isLocalPortFree(host, port)) {
return port;
}
port = ThreadLocalRandom.current().nextInt(from, to);
if (System.currentTimeMillis() - startTime > 30000) {
throw new TimeoutException("Cannot find an available port in the specified range");
}
} while (true);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.broadlink.internal.BroadlinkProtocol;
Expand Down Expand Up @@ -67,6 +68,10 @@ public static void discoverDevices(Logger logger) {
BroadlinkSocket.sendMessage(message, "255.255.255.255", 80, logger);
} catch (UnknownHostException e) {
logger.warn("Failed to initiate discovery: {}", e.getMessage());
} catch (IllegalArgumentException e) {
logger.warn("Failed to find free port: {}", e.getMessage());
} catch (TimeoutException e) {
logger.warn("Cannot find a port to discovber new devices");
}
}

Expand Down

0 comments on commit c3d7819

Please sign in to comment.