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