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 a random
24   * 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 default
35       * {@link ServerSocketFactory}.
36       * 
37       * @return socket
38       * @throws IOException
39       */
40      public static ServerSocket createServerSocket() throws IOException {
41          return createServerSocket(ServerSocketFactory.getDefault());
42      }
43  
44      /**
45       * Creates a new {@link ServerSocket} bound to a random unused port.
46       * 
47       * @param socketFactory socket factory that will be used to create the socket
48       * @return socket
49       * @throws IOException
50       */
51      public static ServerSocket createServerSocket(ServerSocketFactory socketFactory) throws IOException {
52          ServerSocket socket = null;
53          int retries = 10;
54          while (retries-- > 0 && socket == null) {
55              int port = (int) ((65536 - 1024) * Math.random()) + 1024;
56              try {
57                  socket = socketFactory.createServerSocket(port);
58              } catch (BindException ex) {
59                  // try again with different port
60              }
61          }
62          if (socket == null) {
63              throw new BindException("cannot find an unused port to bind");
64          }
65          return socket;
66      }
67  
68  }