Java InetAddress findUnusedPort(InetAddress address, int from, int to)

Here you can find the source of findUnusedPort(InetAddress address, int from, int to)

Description

find Unused Port

License

Open Source License

Declaration

private static int findUnusedPort(InetAddress address, int from, int to) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2000, 2006 IBM Corporation and others.
 * 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:/*from  w w w  .j  av  a2s .  co  m*/
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

import java.io.*;
import java.net.*;
import java.util.*;

public class Main {
    private static final Random random = new Random(System.currentTimeMillis());

    private static int findUnusedPort(InetAddress address, int from, int to) {
        for (int i = 0; i < 12; i++) {
            ServerSocket ss = null;
            int port = getRandomPort(from, to);
            try {
                ss = new ServerSocket();
                SocketAddress sa = new InetSocketAddress(address, port);
                ss.bind(sa);
                return ss.getLocalPort();
            } catch (IOException e) {
            } finally {
                if (ss != null) {
                    try {
                        ss.close();
                    } catch (IOException ioe) {
                    }
                }
            }
        }
        return -1;
    }

    private static int getRandomPort(int low, int high) {
        return (int) (random.nextFloat() * (high - low)) + low;
    }
}

Related

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