Monday 28 September 2015

Java: Find all available ports

In this post, I am going to explain how to get all available ports in your machine using ‘ServerSocket’ class.

public ServerSocket(int port) throws IOException
Create a ServerSocket instance, if the port is available, else throws IOException. The port number is an unsigned 16-bit integer, so there are maximum of 65535 ports. If you pass the argument port as 0, then port number is automatically allocated.

Following snippet is used to get all available ports.

for (int port = 1; port < 65535; port++) {
         try {
                  ServerSocket socket = new ServerSocket(port);
                  socket.close();
                  availablePorts.add(port);
         } catch (IOException e) {
                                   
         }
}


Following is the complete working application.
import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;

public class PortsChecker {

 public static List<Integer> getAvailablePorts() {
  List<Integer> availablePorts = new ArrayList<>();
  for (int port = 1; port < 65535; port++) {
   try {
    ServerSocket socket = new ServerSocket(port);
    socket.close();
    availablePorts.add(port);
   } catch (IOException e) {

   }
  }
  return availablePorts;
 }

 public static void main(String args[]) {
  List<Integer> ports = getAvailablePorts();

  ports.stream().forEach(System.out::println);
 }

}



No comments:

Post a Comment