Advertisement
DanFloyd

PortScanner

Sep 25th, 2015
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1.  
  2. import java.net.*;
  3. import java.util.concurrent.Executors;
  4. import java.util.concurrent.ExecutorService;
  5.  
  6. // Multithreaded port scanner
  7. public class PortScanner {
  8.    
  9.     private int start_port, end_port; // range of ports to scan
  10.     private int timeout = 0; // timeout for the probe
  11.     private String host_name; // host name
  12.     private InetAddress host_address; // host address
  13.     private ExecutorService thread_pool; // thread pool
  14.    
  15.     // Constructor
  16.     public PortScanner (int start_port, int end_port, String host_name) throws PortException, HostException {
  17.         // checking ports
  18.         if (start_port < 0 || end_port < 0 || start_port > end_port || end_port > 65535)
  19.             throw new PortException("Ports must be integers greater than zero and start port must be lower than end port");
  20.         // checking address
  21.         try {
  22.             host_address = InetAddress.getByName(host_name);
  23.         } catch (UnknownHostException e) {
  24.             throw new HostException("Host unreachable");
  25.         }
  26.         // setting properties
  27.         this.setHostName(host_name);
  28.         this.setStartPort(start_port);
  29.         this.setEndPort(end_port);
  30.         // creating thread pool
  31.         thread_pool = Executors.newFixedThreadPool(100);
  32.     }
  33.    
  34.     // Getters and setters
  35.     public int getStartPort () { return start_port;}
  36.     public int getEndPort () { return end_port;}
  37.     public int getTimeout() { return timeout; }
  38.     public String getHostName () { return host_name;}
  39.     public void setStartPort (int v) { start_port = v; }
  40.     public void setEndPort (int v) { end_port = v; }
  41.     public void setTimeout (int v) { timeout = v; }
  42.     public void setHostName (String v) { host_name = v; }
  43.    
  44.     // Starts the PortScanner
  45.     public void startScan() throws PortException {
  46.         int pt = getStartPort(), ep = getEndPort();
  47.         while (pt <= ep) {
  48.             thread_pool.execute(new Probe(host_address, pt, timeout));
  49.             pt ++;
  50.         }
  51.         thread_pool.shutdown(); // shut down the pool
  52.     }
  53.    
  54.     // Terminates the PortScanner
  55.     public void stopScan() {
  56.         // forcing termination
  57.         thread_pool.shutdownNow();
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement