private ServerSocket get(String hostname, Supplier<Integer> randomPortMaker) {
    ServerSocket ss = null;
    int port = -1;
    while (true) {
      port = randomPortMaker.get();
      try {
        ss = new ServerSocket();
        ss.bind(new InetSocketAddress(hostname, port));
        break;
      } catch (IOException ioe) {
        LOG.warn("Failed bind", ioe);
        try {
          ss.close();
        } catch (IOException ioe2) {
          LOG.warn("FAILED CLOSE of failed bind socket", ioe2);
        }
      }
    }
    return ss;
  }
Returns Returns a bound socket; be sure to close when done.
hbase-common/src/test/java/org/apache/hadoop/hbase/net/BoundSocketMaker.java