Here you can find the source of isPortAvailable(String hostname, int port)
Parameter | Description |
---|---|
hostname | the address to check for. |
port | the port to check for. |
true
if the port is available, otherwise false
.
public static boolean isPortAvailable(String hostname, int port)
//package com.java2s; /******************************************************************************* * Copyright (c) 2008, 2010 VMware Inc./*from ww w . j a v a 2 s .c om*/ * 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: * VMware Inc. - initial contribution *******************************************************************************/ import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; public class Main { /** * Checks whether the supplied port is available on any local address. * * @param port the port to check for. * @return <code>true</code> if the port is available, otherwise <code>false</code>. */ public static boolean isPortAvailable(int port) { ServerSocket socket; try { socket = new ServerSocket(); } catch (IOException e) { throw new IllegalStateException("Unable to create ServerSocket.", e); } try { InetSocketAddress sa = new InetSocketAddress(port); socket.bind(sa); return true; } catch (IOException ex) { return false; } finally { try { socket.close(); } catch (IOException ex) { } } } /** * Checks whether the supplied port is available on the specified address. * * @param hostname the address to check for. * @param port the port to check for. * @return <code>true</code> if the port is available, otherwise <code>false</code>. */ public static boolean isPortAvailable(String hostname, int port) { ServerSocket socket; try { socket = new ServerSocket(); } catch (IOException e) { throw new IllegalStateException("Unable to create ServerSocket.", e); } try { InetSocketAddress sa = new InetSocketAddress(hostname, port); socket.bind(sa); return true; } catch (IOException ex) { return false; } finally { try { socket.close(); } catch (IOException ex) { } } } }