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 ServerSocket serverSocket = null;
71
72 try {
73
74 serverSocket = new ServerSocket(0);
75 int port = serverSocket.getLocalPort();
76
77
78 serverSocket.close();
79
80 return port;
81 } catch (IOException ioe) {
82 throw new NoSuchElementException(ioe.getMessage());
83 }
84 }
85
86
87
88
89
90
91
92 public static int getNextAvailable(int fromPort) {
93 if (fromPort < MIN_PORT_NUMBER || fromPort > MAX_PORT_NUMBER) {
94 throw new IllegalArgumentException("Invalid start port: " + fromPort);
95 }
96
97 for (int i = fromPort; i <= MAX_PORT_NUMBER; i++) {
98 if (available(i)) {
99 return i;
100 }
101 }
102
103 throw new NoSuchElementException("Could not find an available port " + "above " + fromPort);
104 }
105
106
107
108
109
110
111 public static boolean available(int port) {
112 if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
113 throw new IllegalArgumentException("Invalid start port: " + port);
114 }
115
116 ServerSocket ss = null;
117 DatagramSocket ds = null;
118
119 try {
120 ss = new ServerSocket(port);
121 ss.setReuseAddress(true);
122 ds = new DatagramSocket(port);
123 ds.setReuseAddress(true);
124 return true;
125 } catch (IOException e) {
126
127 } finally {
128 if (ds != null) {
129 ds.close();
130 }
131
132 if (ss != null) {
133 try {
134 ss.close();
135 } catch (IOException e) {
136
137 }
138 }
139 }
140
141 return false;
142 }
143
144
145
146
147
148
149
150
151
152 public static Set<Integer> getAvailablePorts(int fromPort, int toPort) {
153 if (fromPort < MIN_PORT_NUMBER || toPort > MAX_PORT_NUMBER || fromPort > toPort) {
154 throw new IllegalArgumentException("Invalid port range: " + fromPort + " ~ " + toPort);
155 }
156
157 Set<Integer> result = new TreeSet<Integer>();
158
159 for (int i = fromPort; i <= toPort; i++) {
160 ServerSocket s = null;
161
162 try {
163 s = new ServerSocket(i);
164 result.add(new Integer(i));
165 } catch (IOException e) {
166
167 } finally {
168 if (s != null) {
169 try {
170 s.close();
171 } catch (IOException e) {
172
173 }
174 }
175 }
176 }
177
178 return result;
179 }
180 }