Here you can find the source of findFreePort()
-1
if port not found
public static int findFreePort()
//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; } } }