File tree Expand file tree Collapse file tree
core-java-modules/core-java-networking-3/src/test/java/com/baeldung/socket Expand file tree Collapse file tree Original file line number Diff line number Diff line change 99
1010import java .io .IOException ;
1111import java .net .ServerSocket ;
12- import java .util .Random ;
1312
1413import static org .assertj .core .api .Assertions .assertThat ;
1514import static org .assertj .core .api .Assertions .fail ;
@@ -148,19 +147,10 @@ private int[] getFreePorts() {
148147 }
149148
150149 private int getFreePort () {
151- return new Random ()
152- .ints (36000 , 65000 )
153- .filter (FindFreePortUnitTest ::isFree )
154- .findFirst ()
155- .orElse (DEFAULT_RANDOM_PORT );
156- }
157-
158- private static boolean isFree (int port ) {
159- try {
160- new ServerSocket (port ).close ();
161- return true ;
162- } catch (IOException e ) {
163- return false ;
150+ try (ServerSocket serverSocket = new ServerSocket (0 )){
151+ return serverSocket .getLocalPort ();
152+ } catch (IOException ex ){
153+ return DEFAULT_RANDOM_PORT ;
164154 }
165155 }
166156}
You can’t perform that action at this time.
0 commit comments