Wednesday, April 13, 2016

Create ServerSocket with automatically allocated port

Create ServerSocket by calling constructor ServerSocket(int port) with port = 0,  the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.

Example:
package javaechoserver;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaEchoServer {

    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        try {
            //Get a available port by passing 0 
            serverSocket = new ServerSocket(0);
            int port = serverSocket.getLocalPort();
            System.out.println("Port : " + port);
            
        } catch (IOException ex) {
            Logger.getLogger(JavaEchoServer.class.getName())
                    .log(Level.SEVERE, null, ex);
        } finally {
            if (serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException ex) {
                    Logger.getLogger(JavaEchoServer.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
            }
        }
    }
    
}



No comments:

Post a Comment