Sunday, July 10, 2011

simple Port Scanner

Back in my sixth semester Computer Networks lab, we had to write a simple port scanner (port 0 to 1024). The basic principle was to see whether a connection could be made at a port. If connection can be made, it is open, or else it is closed. I had used the following code then. However, it took 17 minutes to perform the scan.

import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class port_scanner { static Socket soc; public static void main(String[] args) throws IOException { for(int i=1;i<1024;i++){ try{ soc= new Socket(InetAddress.getLocalHost(),i); System.out.println("port "+i+" open"); soc.close(); }catch(IOException e){ System.out.println("port "+i+" closed"); } } } }

The better option was to use threading. I was lazy back then and the above program was sufficient to fetch me marks, and so I did not write a multi-threaded code. I needed to brush up threading because placements are going to start soon. Therefore, I implemented the multi-threaded version. It took just 2 seconds to perform the scan.

import java.io.IOException; import java.net.InetAddress; import java.net.Socket; class myThread implements Runnable{ Thread t; Socket soc; boolean state=true; int port; myThread(int port){ this.port=port; t=new Thread(this,"Thread"); t.start(); } boolean getState(){ return state; } @Override public void run(){ try{ soc= new Socket(InetAddress.getLocalHost(),port); soc.close(); }catch(IOException e){ state=false; } } } public class new_prt { static myThread threads[] = new myThread[1024]; public static void main(String args[]){ for(int j=0;j<1024;j++){ threads[j]=new myThread(i); } for(int j=0;j<1024;j++){ try{ threads[j].t.join(); if(threads[j].getState()==true) System.out.println("port "+threads[j].port + " open"); else System.out.println("port "+threads[j].port + " closed"); }catch(InterruptedException e){ } } } }

No comments:

Post a Comment