Pages

Ads 468x60px

Thursday, September 25, 2014

Java: Find Open Ports in a Range




This code will help you to find system available open ports in a range. You can use it in Java or Android applications according to the scenario.



import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;


public class SystemPorts {

public static void main(String[] args){
getFreePorts();
}

public static void getFreePorts() {

final int MAXIMUM_PORT_RANGE = 6000;
final int MINIMUM_PORT_RANGE = 5000;
int[] ports = new int[1001];
ArrayList<Integer> avialablePorts = new ArrayList<Integer>();

for (int j = 0, i = MINIMUM_PORT_RANGE; i <= MAXIMUM_PORT_RANGE ; i++, j++) {
ports[j] = i;
}

for (int i=0; i<ports.length; i++) {
try {
ServerSocket socket = new ServerSocket(ports[i]);
socket.close();
if(socket.isClosed()){
avialablePorts.add(ports[i]);
System.out.println("Port Number: " + ports[i]);
}
} catch (IOException ex) {
continue; // try next port
}
}
}

}

No comments:

Post a Comment