View Javadoc
1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.net.server.test;
15  
16  import java.io.IOException;
17  import java.net.BindException;
18  import java.net.ServerSocket;
19  
20  import javax.net.ServerSocketFactory;
21  
22  /**
23   * Static utility methods for obtaining a {@link ServerSocket} bound to
24   * a random unused port.
25   *
26   * @author Carl Harris
27   */
28  public class ServerSocketUtil {
29  
30      /**
31       * Creates a new {@link ServerSocket} bound to a random unused port.
32       * <p>
33       * This method is a convenience overload for 
34       * {@link #createServerSocket(ServerSocketFactory)} using the platform's
35       * default {@link ServerSocketFactory}.
36       * @return socket
37       * @throws IOException
38       */
39      public static ServerSocket createServerSocket() throws IOException {
40          return createServerSocket(ServerSocketFactory.getDefault());
41      }
42  
43      /**
44       * Creates a new {@link ServerSocket} bound to a random unused port.
45       * @param socketFactory socket factory that will be used to create the 
46       *    socket
47       * @return socket
48       * @throws IOException
49       */
50      public static ServerSocket createServerSocket(ServerSocketFactory socketFactory) throws IOException {
51          ServerSocket socket = null;
52          int retries = 10;
53          while (retries-- > 0 && socket == null) {
54              int port = (int) ((65536 - 1024) * Math.random()) + 1024;
55              try {
56                  socket = socketFactory.createServerSocket(port);
57              } catch (BindException ex) {
58                  // try again with different port
59              }
60          }
61          if (socket == null) {
62              throw new BindException("cannot find an unused port to bind");
63          }
64          return socket;
65      }
66  
67  }