Java HTTP Port Find findFreePort()

Here you can find the source of findFreePort()

Description

Find free unused TCP port.

License

Open Source License

Return

free port or -1 if port not found

Declaration

public static int findFreePort() 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2014 Axmor Inc.// w ww .  j a  v a  2 s.co  m
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

import java.io.IOException;
import java.net.ServerSocket;

public class Main {
    /**
     * Find free unused TCP port.
     * 
     * @return free port or <code>-1</code> if port not found
     */
    public static int findFreePort() {
        try (ServerSocket socket = new ServerSocket(0)) {
            return socket.getLocalPort();
        } catch (IOException e) {
            return -1;
        }
    }
}

Related

  1. findFreePort()
  2. findFreePort()
  3. findFreePort()
  4. findFreePort()
  5. findFreePort()
  6. findFreePort(int start, int len)
  7. findFreePort(int start, int limit)
  8. findFreePort(int startPort)
  9. findFreePort(int startPort)