Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  * See the file LICENSE for redistribution information.
  * Copyright (c) 2010, 2013 Oracle and/or its affiliates.  All rights reserved.
An iterator to iterate over the free ports on an interface.
public class FreePortLocator {
    private final String hostname;
    private final int portStart;
    private final int portEnd;
    private int currPort;

Constructor identifying the interface and the port range within which to look for free ports.
    public FreePortLocator(String hostnameint portStartint portEnd) {
        assert portStart < portEnd;
        this. = hostname;
        this. = portStart;
        this. = portEnd;
         = portStart;

Returns the next free port. Note that it's possible that on a busy machine another process may grab the "free" port before it's actually used.
    public int next() {
        ServerSocket serverSocket = null;
        while (++ < ) {
            try {

Try a couple different methods to be sure that the port is truly available.
                serverSocket = new ServerSocket();

Now using the hostname.
                serverSocket = new ServerSocket();
                InetSocketAddress sa =
                    new InetSocketAddress();
                return ;
            } catch (IOException e) {
                /* Try the next port number. */
        throw new IllegalStateException
            ("No more ports avaliable in the range: " +
              + " - " + );

Skip a number of ports.
    public void skip(int num) {
         += num;
New to GrepCode? Check out our FAQ X