|
16 | 16 |
|
17 | 17 | package io.appulse.utils; |
18 | 18 |
|
| 19 | +import static java.util.Optional.empty; |
| 20 | +import static java.util.Optional.of; |
| 21 | +import static java.util.concurrent.TimeUnit.SECONDS; |
| 22 | + |
19 | 23 | import java.io.ByteArrayOutputStream; |
20 | 24 | import java.io.EOFException; |
| 25 | +import java.io.IOException; |
21 | 26 | import java.io.InputStream; |
| 27 | +import java.net.InetSocketAddress; |
22 | 28 | import java.net.Socket; |
| 29 | +import java.util.Optional; |
23 | 30 |
|
24 | 31 | import lombok.NonNull; |
25 | 32 | import lombok.SneakyThrows; |
|
28 | 35 | /** |
29 | 36 | * |
30 | 37 | * @author Artem Labazin |
31 | | - * @since 1.1.0 |
| 38 | + * @since 1.2.0 |
32 | 39 | */ |
33 | | -public final class StreamReader { |
| 40 | +public final class SocketUtils { |
| 41 | + |
| 42 | + public static Optional<Integer> findFreePort () { |
| 43 | + return findFreePort(1024, 65535); |
| 44 | + } |
| 45 | + |
| 46 | + public static Optional<Integer> findFreePort (int from, int to) { |
| 47 | + for (int port = from; port <= to; port++) { |
| 48 | + if (isPortAvailable(port)) { |
| 49 | + return of(port); |
| 50 | + } |
| 51 | + } |
| 52 | + return empty(); |
| 53 | + } |
| 54 | + |
| 55 | + public static boolean isPortAvailable (int port) { |
| 56 | + try (Socket socket = new Socket()) { |
| 57 | + socket.connect(new InetSocketAddress("localhost", port), (int) SECONDS.toMillis(1)); |
| 58 | + return false; |
| 59 | + } catch (IOException ex) { |
| 60 | + return true; |
| 61 | + } |
| 62 | + } |
34 | 63 |
|
35 | 64 | @SneakyThrows |
36 | 65 | public static byte[] read (@NonNull InputStream stream) { |
@@ -98,6 +127,6 @@ public static Bytes readBytes (@NonNull Socket socket, int fixedLength) { |
98 | 127 | return readBytes(socket.getInputStream(), fixedLength); |
99 | 128 | } |
100 | 129 |
|
101 | | - private StreamReader () { |
| 130 | + private SocketUtils () { |
102 | 131 | } |
103 | 132 | } |
0 commit comments