find Free Port - Java Network

Java examples for Network:Socket

Description

find Free Port

Demo Code


//package com.java2s;
import java.io.IOException;

import java.net.ServerSocket;

public class Main {
    public static int findFreePort() {
        try {/*from w  w  w . j a  v  a  2  s  . c  o m*/
            ServerSocket server = new ServerSocket(0);
            int port = server.getLocalPort();
            server.close();
            return port;
        } catch (IOException e) {
            throw new RuntimeException(
                    "Failed to find free local port to bind the agent to",
                    e);
        }
    }
}

Related Tutorials