Skip to content

Commit

Permalink
exclude 0 in the free ports
Browse files Browse the repository at this point in the history
  • Loading branch information
virajjasani committed Mar 3, 2022
1 parent bcf8a15 commit 68e7e2e
Showing 1 changed file with 9 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -1056,15 +1056,22 @@ public static int getFreeSocketPort() {
/**
* Return free ports. There is no guarantee they will remain free, so
* ports should be used immediately. The number of free ports returned by
* this method should match argument {@code numOfPorts}.
* this method should match argument {@code numOfPorts}. Num of ports
* provided in the argument should not exceed 25.
*
* @param numOfPorts Number of free ports to acquire.
* @return Free ports for binding a local socket.
*/
public static Set<Integer> getFreeSocketPorts(int numOfPorts) {
Preconditions.checkArgument(numOfPorts > 0 && numOfPorts <= 25,
"Valid range for num of ports is between 0 and 26");
final Set<Integer> freePorts = new HashSet<>(numOfPorts);
for (int i = 0; i < numOfPorts * 5; i++) {
freePorts.add(getFreeSocketPort());
int port = getFreeSocketPort();
if (port == 0) {
continue;
}
freePorts.add(port);
if (freePorts.size() == numOfPorts) {
return freePorts;
}
Expand Down

0 comments on commit 68e7e2e

Please sign in to comment.