Here you can find the source of isPortInUse(int port)
Parameter | Description |
---|---|
port | the port to check |
true
if the port is used, false
if it is available.
public static boolean isPortInUse(int port)
//package com.java2s; /******************************************************************************* * Copyright (c) 2016 Red Hat./* w ww .ja 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 * * Contributors: * Red Hat - Initial Contribution *******************************************************************************/ import java.io.IOException; import java.net.ServerSocket; public class Main { /** * Checks if the given port is already used * * @param port * the port to check * @return <code>true</code> if the port is used, <code>false</code> if it * is available. */ public static boolean isPortInUse(int port) { if (port < 0 || port >= 65536) { return false; } try (ServerSocket socket = new ServerSocket(port)) { //not in use return false; } catch (IOException e) { return true;//in use } } }