Reputation: 20092
I have the following piece of code that checks whether port 443 is open in a given host.
import java.net.*;
import java.io.IOException;
public class Scan {
public static void main (String[] args) {
String host="put hostname here";
int port=443;
try{
Socket s = new Socket(host,port);
System.out.println("Can listen on port "+port+
" in host "+host+" is open");
} //end try
catch (IOException ex)
{
//remote host is not listening on port 443
System.out.println("Can not listen on port "+port+
" of host "+host);
} //end catch
}
}
My question is: If port 443 is not open in a certain host, this make my program very slow, as I need to check group of hosts. Is there any way to improve the code to make scanning port 443 faster while maintain reliability at the same time? Is there any ways using java programming to make port scanning other than using sockets ?
Please not that pinging before scan will not help, as the hostnames I have are connected, I only need to check if port 443 is open or closed.
Upvotes: 0
Views: 905
Reputation: 22030
If you have to scan a group of hosts, just run each check in a separate thread. This will make sure one host does not keep you from handling the others.
Long and independent IO operations are a classic usecase for multithreading. You don't even have to worry about the number of CPUs on your machine, because they will practically do nothing while waiting for the network response. Adding a timeout, as suggested by others, is also a reasonable addition, and can be used in addition to multithreading.
Upvotes: 2