Java Snippet – Port Finder

PortFinder.java

import java.io.IOException;
import java.net.*;

public class PortFinder
{

    public PortFinder()
    {
    }

    public static synchronized int findUnusedPort()
    {
        return findUnusedPort(0);
    }

    public static boolean isPortUnused(int port)
    {
        return findUnusedPort(port) != -1;
    }

    private static int findUnusedPort(int port)
    {
        ServerSocket ss = null;
        int j;
        if(!isWindows() && !isMacos())
            break MISSING_BLOCK_LABEL_63;
        ss = new ServerSocket();
        SocketAddress sa = new InetSocketAddress("127.0.0.1", port);
        ss.bind(sa);
        ss.setReuseAddress(true);
        j = ss.getLocalPort();
        if(ss != null)
            try
            {
                ss.close();
            }
            catch(IOException ioexception3) { }
        return j;
        int i;
        try
        {
            ss = new ServerSocket(port);
            ss.setReuseAddress(true);
            i = ss.getLocalPort();
        }
        catch(IOException ioexception)
        {
            if(ss != null)
                try
                {
                    ss.close();
                }
                catch(IOException ioexception1) { }
            break MISSING_BLOCK_LABEL_130;
        }
        if(ss != null)
            try
            {
                ss.close();
            }
            catch(IOException ioexception2) { }
        return i;
        Exception exception;
        exception;
        if(ss != null)
            try
            {
                ss.close();
            }
            catch(IOException ioexception4) { }
        throw exception;
        return -1;
    }

    private static boolean isMacos()
    {
        return OS_NAME.toLowerCase().startsWith("mac");
    }

    private static boolean isWindows()
    {
        return OS_NAME.toLowerCase().startsWith("win");
    }

    private static final String OS_NAME = System.getProperty("os.name");

}

Leave a Reply