Simple Java Port Scanner

/**
 * A Simple MultiThreaded Port Scanner
 * @author  martin@spamer.me.uk
 * Created on 22 September 2004, 12:55
 */
package uk.me.spamer.portscan;
 
/**
 * A Threaded Class to open a ports at an IP address.
 * @author  martin.spamer
 */
public class PortScan
  extends java.lang.Thread
{
  private String ip = null;
  private int port = 0;
  private boolean reportClosedPort = false;
  static private int loadFactor = 100 ;
  static private java.util.Properties properties = new java.util.Properties() ;
 
  /** 
   * Creates a new instance of PortScan 
   **/
  public PortScan(String ip, int port)
    {
    super() ;
 
    this.ip = ip ;
    this.port = port ;
    }
 
  /**
   * try looking up a port 
   * @param portNo
   * @return String description of 
   */
  public String lookUpPort(int port)
    {
      return properties.getProperty( Integer.toString( port ),"unknown" ) ; 
    }
 
  /**
   * scan the port
   **/
  public void run()
    {
    try
      {
      java.net.Socket socket = new java.net.Socket( ip, port ) ;
 
      // report open port & try looking it up      
      System.out.println( "scanning="+ip+":"+port+" open. "+lookUpPort( port ) ) ;
 
      Thread.yield() ;
 
      socket.close() ;
      }
    catch(Exception exception)
      {
      if (reportClosedPort == true)
        {
        System.err.println( "portscan="+ip+":"+port+" "+exception.getMessage() ) ;
        }
      }
    }
 
  /**
   * @param args the command line arguments
   * iSeries 128.1.0.12
   */
  public static void main(String[] args)
    {
    // validate the port number
    try
      {
      System.out.println( "PortScan IP:" + args[0] ) ;
 
      properties.load( new java.io.FileInputStream( new java.io.File( "ports.properties" ) ) ) ;    
 
      for(int port=1 ; port < (64*1024) ; )
        {
          if ( Thread.activeCount() > loadFactor )
            {
            Thread.yield() ;
            }
          else
            {
            PortScan portScan = new PortScan( args[0], port) ;
            portScan.start() ;
            port++ ;
            }
        }
      }
    catch(Exception exception)
      {
      System.err.println( "Command line must include IP address" ) ;
      }
    }
}

oo_java_portscan.txt ยท Last modified: 2013/01/30 18:09 by Martin Spamer