From 9f36d170bed59c4801f45c01ae23c89bab3a36ae Mon Sep 17 00:00:00 2001 From: Tony Mitchell Date: Wed, 6 Dec 2017 16:38:46 -0800 Subject: [PATCH] Support identical minPort and maxPort in SocketUtils (#1612) This commit fixes a bug where an IllegalStateException was thrown if the minPort and maxPort values supplied to SocketUtils.findAvailableTcpPort(int, int) were identical. --- .../main/java/org/springframework/util/SocketUtils.java | 2 +- .../java/org/springframework/util/SocketUtilsTests.java | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/spring-core/src/main/java/org/springframework/util/SocketUtils.java b/spring-core/src/main/java/org/springframework/util/SocketUtils.java index 2c3b849c51..5d8df68a67 100644 --- a/spring-core/src/main/java/org/springframework/util/SocketUtils.java +++ b/spring-core/src/main/java/org/springframework/util/SocketUtils.java @@ -258,7 +258,7 @@ public class SocketUtils { int candidatePort; int searchCounter = 0; do { - if (++searchCounter > portRange) { + if (searchCounter++ > portRange) { throw new IllegalStateException(String.format( "Could not find an available %s port in the range [%d, %d] after %d attempts", name(), minPort, maxPort, searchCounter)); diff --git a/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java b/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java index 8abd6c8878..b2a45d8a20 100644 --- a/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java +++ b/spring-core/src/test/java/org/springframework/util/SocketUtilsTests.java @@ -53,6 +53,13 @@ public class SocketUtilsTests { assertPortInRange(port, PORT_RANGE_MIN, PORT_RANGE_MAX); } + @Test + public void findAvailableTcpPortWithMinPortEqualToMaxPort() { + int minMaxPort = SocketUtils.findAvailableTcpPort(); + int port = SocketUtils.findAvailableTcpPort(minMaxPort, minMaxPort); + assertEquals(minMaxPort, port); + } + @Test(expected = IllegalStateException.class) public void findAvailableTcpPortWhenPortOnLoopbackInterfaceIsNotAvailable() throws Exception { int port = SocketUtils.findAvailableTcpPort();