For purpose of practice and experience, I was working on a "Port Availability Scanner" written in Java. So far it's working but it's really slow. Especially on relatively large quantities of ports (1000+).
It's quite faster scanning localhost then my external IP (If it actually scans externally correctly).
As an additional note for if it really matters: I am using Java 9.
Code:
package test;
import java.io.IOException;
import java.net.Socket;
import java.util.Arrays;
public class Test {
private static final Test instance = new Test("157.97.56.42", 80, 443, 21, 22, 25, 8080);
private static String ip;
private int[] ports = new int[1_000_000];
private Test(String ip, int start, int end) {
Test.ip = ip;
ports: {
int c = 0;
for (int i = start; i < end; i++) {
ports[c++] = i;
}
ports = Arrays.copyOfRange(ports, 0, c + 1);
}
}
private Test(String ip, int... ports) {
Test.ip = ip;
this.ports = ports;
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
Thread thread = new Thread(instance::check);
thread.start();
long end = System.currentTimeMillis();
System.out.println("Took: " + (end - start) + "ms.");
}
public void check() {
if(ports.length > 1) {
for (int port : ports) {
System.out.println("Available " + port + ": " + Test.isAvailable(port));
}
} else if(ports.length == 1) {
System.out.println("Available " + ports[0] + ": " + Test.isAvailable(ports[0]));
} else {
throw new IllegalStateException();
}
}
private static boolean isAvailable(int port) {
Socket socket = null;
try {
socket = new Socket(ip, port);
return false;
} catch (IOException e) {
return true;
} finally {
if(socket != null) {
try {
socket.close();
} catch (IOException ignored) { }
}
}
}
}
Please can you review my code, especially performance-wise?
Edit: Would it be possible by using NIO or any other form of MultiThreading the sake of speed?