Java InetAddress findFreePort(InetAddress address, int start, int end)

Here you can find the source of findFreePort(InetAddress address, int start, int end)

Description

Find free port in range for the specified IP address

License

Open Source License

Return

int

Declaration

public static int findFreePort(InetAddress address, int start, int end) 

Method Source Code

//package com.java2s;
/**//  ww w .j  a va 2  s  . c o m
 * Aptana Studio
 * Copyright (c) 2005-2011 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the GNU Public License (GPL) v3 (with exceptions).
 * Please see the license.html included with this distribution for details.
 * Any modifications to this file must keep this entire header intact.
 */

import java.io.IOException;

import java.net.InetAddress;

import java.net.ServerSocket;

public class Main {
    /**
     * Find free port for the specified IP address
     * 
     * @return int
     */
    public static int findFreePort(InetAddress address) {
        ServerSocket socket = null;
        try {
            socket = new ServerSocket(0, 0, address);
            socket.setReuseAddress(true);
            return socket.getLocalPort();
        } catch (IOException ignore) {
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException ignore) {
                }
            }
        }
        return -1;
    }

    /**
     * Find free port in range for the specified IP address
     * 
     * @return int
     */
    public static int findFreePort(InetAddress address, int start, int end) {
        ServerSocket socket = null;
        try {
            for (int port = start; port <= end; ++port) {
                try {
                    socket = new ServerSocket(port, 0, address);
                    socket.setReuseAddress(true);
                    return socket.getLocalPort();
                } catch (IOException ignore) {
                }
            }
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException ignore) {
                }
            }
        }
        return -1;
    }
}

Related

  1. createDatagramSocket(InetAddress addr, int port)
  2. createInetSocketAddress(final InetAddress address)
  3. createResolved(InetAddress address, int port)
  4. createSocket(InetAddress address, int port, boolean fixedPort)
  5. doMatch(InetAddress inetAddress, String toMatchParam)
  6. findUnusedPort(InetAddress address, int from, int to)
  7. findUnusedPort(InetAddress address, int low, int high)
  8. formatAddress(InetAddress address, int port, Context cx, Scriptable scope)
  9. formatAddress(InetAddress inet)