I usually use the socket method to check if a port is open public class NewClass {
public static void main(String[] args) throws IOException, InterruptedException {
long startTime = System.currentTimeMillis();
List<String> ips = FileUtils.readLines(new File("ip.txt"), "utf-8");
if (!ips.isEmpty()) {
ExecutorService executorService = Executors.newFixedThreadPool(100);
for (String ip : ips) {
executorService.execute(() -> {
if ("nmap".equals(args[0])) {
checkPortNmap(ip);
} else {
checkPort(ip);
}
});
}
executorService.shutdown();
executorService.awaitTermination(60, TimeUnit.SECONDS);
while (!executorService.isTerminated()) {
}
}
System.out.println(args[0] + "\t" + TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startTime));
}
public static String checkPort(String ip) {
System.out.println("SOCK: " + ip);
String message = "ok";
try {
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(ip, 22), 6000);
}
} catch (IOException ex) {
message = ex.getMessage();
}
return message;
}
private static void checkPortNmap(String ip) {
ProcessBuilder processBuilder = new ProcessBuilder().redirectErrorStream(true);
processBuilder.command("bash", "-c", "nmap -Pn -sS -p22 " + ip);
if (showProcess(processBuilder)) {
System.out.println("IP: " + ip);
}
}
private static boolean showProcess(ProcessBuilder processBuilder) {
try {
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String read;
while ((read = reader.readLine()) != null) {
System.out.println(read);
if (read.contains("open")) {
return true;
}
}
} catch (IOException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
}
The ways I have implemented for port check
1.Check Port Sock Normal: 60 seconds
2.Check Port Nmap : 120seconds
I heard there is a faster way to check the port using TCP SYN. Reading related topic questions How to implement tcp syn scanning with java code? often recommend jpcap. I the invitee cannot figure out how to use it. Please help me with a simple example code with jpcap or any other library that can help me