java get random open port code example

Example: java - get open ports

import java.io.IOException;
import java.net.Socket;

public class App {
	public static void main(String[] args) {
    	Socket tempSocket = new Socket();	//	Initialize
        boolean isOpened;
      	
      	//	Loop through all the 65536 ports
        for (int port = 0; port < 65536; port++) {
          	//	We will assume the current port is opened unless
          	//	An exception occurs
            isOpened = true;
          
            try {
              	//	Let's try connecting
                tempSocket = new Socket("127.0.0.1", port);
            }
            catch (IOException e) {
              	//	If an IOException occurs, then port is closed
                isOpened = false;
            }
            finally {
              	//	Close the socket to save resources
                tempSocket.close();
            }

          	//	If port is opened print a message to the console
            if (isOpened) {
                String message = String.format("port %d is open", port);
                System.out.println(message);
            }
        }
    } 
}

Tags:

Java Example