■ ■ ■ ■ ■ ■
Projects/Simple_port_scanner/src/main/java/com/scanner/SimpleScanner.java
| 1 | + | package com.scanner; |
| 2 | + | |
| 3 | + | import java.io.IOException; |
| 4 | + | import java.net.InetSocketAddress; |
| 5 | + | import java.net.Socket; |
| 6 | + | import java.util.ArrayList; |
| 7 | + | import java.util.List; |
| 8 | + | import java.util.concurrent.ConcurrentLinkedQueue; |
| 9 | + | import java.util.concurrent.ExecutorService; |
| 10 | + | import java.util.concurrent.Executors; |
| 11 | + | import java.util.concurrent.TimeUnit; |
| 12 | + | import java.util.concurrent.atomic.AtomicInteger; |
| 13 | + | |
| 14 | + | public class SimpleScanner { |
| 15 | + | |
| 16 | + | |
| 17 | + | public static void main(String[] args) { |
| 18 | + | // verification if has ip target |
| 19 | + | if(args.length == 1){ |
| 20 | + | String ipTarget = args[0]; |
| 21 | + | List openPorts = portScan(ipTarget); |
| 22 | + | openPorts.forEach(port -> System.out.println(ipTarget + ", port open: " + port)); |
| 23 | + | } |
| 24 | + | else { |
| 25 | + | System.out.println("Correct usage: script, IP address target"); |
| 26 | + | System.exit(0); |
| 27 | + | } |
| 28 | + | } |
| 29 | + | |
| 30 | + | public static List portScan(String ip) { |
| 31 | + | ConcurrentLinkedQueue openPorts = new ConcurrentLinkedQueue<>(); |
| 32 | + | ExecutorService executorService = Executors.newFixedThreadPool(50); |
| 33 | + | AtomicInteger port = new AtomicInteger(0); |
| 34 | + | while (port.get() < 65535) { |
| 35 | + | final int currentPort = port.getAndIncrement(); |
| 36 | + | executorService.submit(() -> { |
| 37 | + | try { |
| 38 | + | Socket socket = new Socket(); |
| 39 | + | // try connection |
| 40 | + | socket.connect(new InetSocketAddress(ip, currentPort), 200); |
| 41 | + | socket.close(); |
| 42 | + | // if Connection established add to ConcurrentLinkedQueue |
| 43 | + | openPorts.add(currentPort); |
| 44 | + | } |
| 45 | + | catch (IOException e) { |
| 46 | + | } |
| 47 | + | |
| 48 | + | }); |
| 49 | + | } |
| 50 | + | executorService.shutdown(); |
| 51 | + | try { |
| 52 | + | executorService.awaitTermination(10, TimeUnit.MINUTES); |
| 53 | + | } |
| 54 | + | catch (InterruptedException e) { |
| 55 | + | e.printStackTrace(); |
| 56 | + | } |
| 57 | + | |
| 58 | + | List openPortList = new ArrayList<>(); |
| 59 | + | System.out.println("open Ports Queue: " + openPorts.size()); |
| 60 | + | while (!openPorts.isEmpty()) { |
| 61 | + | // after verify turns ConcurrentLinkedQueue into List |
| 62 | + | openPortList.add(openPorts.poll()); |
| 63 | + | } |
| 64 | + | return openPortList; |
| 65 | + | } |
| 66 | + | } |
| 67 | + | |