Sunday, December 15, 2013

Find a free port using Java with ServerSocket(0)

Use the constructor ServerSocket(int port) of java.net.ServerSocket class with 0 to request a free port automatically, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.

Example:
import java.net.ServerSocket;
import java.io.IOException;

class checkSocket
{
    public static void main(String srgs[])
    {
        System.out.println("Hello Raspberry Pi");
        
        try{
            ServerSocket socket0 = new ServerSocket(0);
            System.out.println("Automatically allocated port: " 
                                + socket0.getLocalPort());
        }catch(IOException e){
            System.out.println(e.toString());
        }
        
    }
}

Find a free port using Java with ServerSocket(0)
Find a free port using Java with ServerSocket(0)

No comments: