View Javadoc

1   /*
2    *  Licensed to the Apache Software Foundation (ASF) under one
3    *  or more contributor license agreements.  See the NOTICE file
4    *  distributed with this work for additional information
5    *  regarding copyright ownership.  The ASF licenses this file
6    *  to you under the Apache License, Version 2.0 (the
7    *  "License"); you may not use this file except in compliance
8    *  with the License.  You may obtain a copy of the License at
9    *
10   *    http://www.apache.org/licenses/LICENSE-2.0
11   *
12   *  Unless required by applicable law or agreed to in writing,
13   *  software distributed under the License is distributed on an
14   *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   *  KIND, either express or implied.  See the License for the
16   *  specific language governing permissions and limitations
17   *  under the License.
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   * Finds currently available server ports.
31   *
32   * @author <a href="http://mina.apache.org">Apache MINA Project</a>
33   * @see <a href="http://www.iana.org/assignments/port-numbers">IANA.org</a>
34   */
35  public class AvailablePortFinder {
36      /**
37       * The minimum number of server port number.
38       */
39      public static final int MIN_PORT_NUMBER = 1;
40  
41      /**
42       * The maximum number of server port number.
43       */
44      public static final int MAX_PORT_NUMBER = 49151;
45  
46      /**
47       * Creates a new instance.
48       */
49      private AvailablePortFinder() {
50          // Do nothing
51      }
52  
53      /**
54       * Returns the {@link Set} of currently available port numbers
55       * ({@link Integer}).  This method is identical to
56       * <code>getAvailablePorts(MIN_PORT_NUMBER, MAX_PORT_NUMBER)</code>.
57       *
58       * WARNING: this can take a very long time.
59       */
60      public static Set<Integer> getAvailablePorts() {
61          return getAvailablePorts(MIN_PORT_NUMBER, MAX_PORT_NUMBER);
62      }
63  
64      /**
65       * Gets the next available port starting at the lowest port number.
66       *
67       * @throws NoSuchElementException if there are no ports available
68       */
69      public static int getNextAvailable() {
70          try {
71              // Here, we simply return an available port found by the system
72              return new ServerSocket( 0 ).getLocalPort();
73          } catch (IOException ioe) {
74              throw new NoSuchElementException(ioe.getMessage());
75          }
76      }
77  
78      /**
79       * Gets the next available port starting at a port.
80       *
81       * @param fromPort the port to scan for availability
82       * @throws NoSuchElementException if there are no ports available
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: "
87                      + fromPort);
88          }
89  
90          for (int i = fromPort; i <= MAX_PORT_NUMBER; i++) {
91              if (available(i)) {
92                  return i;
93              }
94          }
95  
96          throw new NoSuchElementException("Could not find an available port "
97                  + "above " + fromPort);
98      }
99  
100     /**
101      * Checks to see if a specific port is available.
102      *
103      * @param port the port to check for availability
104      */
105     public static boolean available(int port) {
106         if (port < MIN_PORT_NUMBER || port > MAX_PORT_NUMBER) {
107             throw new IllegalArgumentException("Invalid start port: " + port);
108         }
109 
110         ServerSocket ss = null;
111         DatagramSocket ds = null;
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             // Do nothing
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                     /* should not be thrown */
130                 }
131             }
132         }
133 
134         return false;
135     }
136 
137     /**
138      * Returns the {@link Set} of currently avaliable port numbers ({@link Integer})
139      * between the specified port range.
140      *
141      * @throws IllegalArgumentException if port range is not between
142      * {@link #MIN_PORT_NUMBER} and {@link #MAX_PORT_NUMBER} or
143      * <code>fromPort</code> if greater than <code>toPort</code>.
144      */
145     public static Set<Integer> getAvailablePorts(int fromPort, int toPort) {
146         if (fromPort < MIN_PORT_NUMBER || toPort > MAX_PORT_NUMBER
147                 || fromPort > toPort) {
148             throw new IllegalArgumentException("Invalid port range: "
149                     + fromPort + " ~ " + toPort);
150         }
151 
152         Set<Integer> result = new TreeSet<Integer>();
153 
154         for (int i = fromPort; i <= toPort; i++) {
155             ServerSocket s = null;
156 
157             try {
158                 s = new ServerSocket(i);
159                 result.add(new Integer(i));
160             } catch (IOException e) {
161                 // Do nothing
162             } finally {
163                 if (s != null) {
164                     try {
165                         s.close();
166                     } catch (IOException e) {
167                         /* should not be thrown */
168                     }
169                 }
170             }
171         }
172 
173         return result;
174     }
175 }