Simple Port Scanner Using java

Hi guys welcome to j2seblog .Today in this post i’m going to show you how to write a simple port scanner in java. By using java programming language we can easily create a simple port scanner with in 15 lines of code.for this  port scanner  we are using Socket class which is located in package.The code for port scanner is shown below and i explain each part of the code


import java.lang.*;
public class PortScanner
public static void main(String[] args)
System.out.println(“eneter ip address and ports range”);
String ip=args[0];
int start_port=Integer.parseInt(args[1]);
int end_port=Integer.parseInt(args[2]);
for(int i=start_port;i<=end_port;i++)
Socket soc=new Socket(ip,i);
System.out.println(“open port : “+i);
}//end of try
catch(Exception e)
System.out.println(“closed port : “+i);
}//end of catch
}//end of for loop
}//end of main method
}//end of class


In this code we are taking ip address and port ranges from command line arguments and converting staring port address and ending port address into int and stores them into start_port and end_port variables respectively.We are using for-loop to iterate over the range of ports between start_port and end_port and for each port we are trying to connect to the target host system using  ” Socket soc=new Socket(ip,i);” statement this statement returns Socket object if the port is opened and it connects to the host machine and in the next two statements we simply print the port is opened and close the connection using “soc.close()” statement.Otherwise if the port is closed and it can’t connect to the target system it throws an error,so the catch block will be executed every time if the port is closed so we simply print the port is closed and and increments the “i” value.



java  PortScanner  100 200


The disadvantages of this port scanner is it is very slow and it is not so reliable.

In my next post i’m going to implement this port scanner using threads to create a multi threaded port scanner.if you have any doubts please  comment them in comment section.

sorry for my english…….