1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.util;
21
22 import java.io.IOException;
23 import java.net.DatagramSocket;
24 import java.net.ServerSocket;
25 import java.util.NoSuchElementException;
26 import java.util.Set;
27 import java.util.TreeSet;
28
29
30
31
32
33
34
35 public class AvailablePortFinder {
36
37
38
39 public static final int MIN_PORT_NUMBER = 1;
40
41
42
43
44 public static final int MAX_PORT_NUMBER = 49151;
45
46
47
48
49 private AvailablePortFinder() {
50
51 }
52
53
54
55
56
57
58
59
60 public static Set<Integer> getAvailablePorts() {
61 return getAvailablePorts(MIN_PORT_NUMBER, MAX_PORT_NUMBER);
62 }
63
64
65
66
67
68
69 public static int getNextAvailable() {
70 try (ServerSocket serverSocket = new ServerSocket(0)){
71
72 return serverSocket.getLocalPort();
73 } catch (IOException ioe) {
74 throw new NoSuchElementException(ioe.getMessage());
75 }
76 }
77
78
79
80
81
82
83
84 public static int getNextAvailable(int fromPort) {
85 if (fromPort < MIN_PORT_NUMBER || fromPort > MAX_PORT_NUMBER) {
86 throw new IllegalArgumentException("Invalid start port: " + fromPort);
87 }
88
89 for (int i = fromPort; i <= MAX_PORT_NUMBER; i++) {
90 if (available(i)) {
91 return i;
92 }
93 }
94
95 throw new NoSuchElementException("Could not find an available port " + "above " + fromPort);
96 }
97
98
99
100
101
102
103
104 public static boolean available(int port) {
105 if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
106 throw new IllegalArgumentException("Invalid start port: " + port);
107 }
108
109 ServerSocket ss = null;
110 DatagramSocket ds = null;
111
112 try {
113 ss = new ServerSocket(port);
114 ss.setReuseAddress(true);
115 ds = new DatagramSocket(port);
116 ds.setReuseAddress(true);
117 return true;
118 } catch (IOException e) {
119
120 } finally {
121 if (ds != null) {
122 ds.close();
123 }
124
125 if (ss != null) {
126 try {
127 ss.close();
128 } catch (IOException e) {
129
130 }
131 }
132 }
133
134 return false;
135 }
136
137
138
139
140
141
142
143
144
145
146
147 public static Set<Integer> getAvailablePorts(int fromPort, int toPort) {
148 if (fromPort < MIN_PORT_NUMBER || toPort > MAX_PORT_NUMBER || fromPort > toPort) {
149 throw new IllegalArgumentException("Invalid port range: " + fromPort + " ~ " + toPort);
150 }
151
152 Set<Integer> result = new TreeSet<>();
153
154 for (int i = fromPort; i <= toPort; i++) {
155 ServerSocket s = null;
156
157 try {
158 s = new ServerSocket(i);
159 result.add(Integer.valueOf(i));
160 } catch (IOException e) {
161
162 } finally {
163 if (s != null) {
164 try {
165 s.close();
166 } catch (IOException e) {
167
168 }
169 }
170 }
171 }
172
173 return result;
174 }
175 }