Simple Port Scanner application using Java

By: Syed M Hussain Emailed: 1700 times Printed: 2205 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

In this article I will explain how to develop a simple port scanner which you can use to scan a host for open ports. A port scanner is a software tool used by network administrators to scan a host network for open ports. This allows the administrator to check their network security.

There are in total 65,535 ports but not every port is used. Below is a few known ports:


Port 20: FTP | Data port
Port 21: FTP | Control (Command) port
Port 23: Telnet | Unencrypted text communications
Port 25: SMTP | Used for e-mail routing between mailservers
Port 80: HTTP | HyperText Transfer Protocol


Above is just a few known ports but there are more and by developing a simple console application in Java we can scan the localhost for any open ports. First lets have a look at the package we need to import into our code.

java.net
The java.net package provides the Classes needed for implementing network applications. One of the Classes is the Socket Class, which implements client sockets. We will use this Class to connect to the localhost and scan through a range of ports.

Now let\'s get started. The port scanner that we will develop will take two command line arguments. The first argument is the start port, this is the port we want to start scanning from. The second argument is the stop port. We will use a For loop to loop through the start and stop ports, each time we increment the loop, we will establish a connection with the localhost and use the incremented loop counter as the port number.

Listing 1.1 below is the complete code of the port scanner with line numbers. Remove the line numbers and save the code as PortScanner.java


1. import java.net.*;

2. public class PortScanner

{

3.        public static void main(String args[])
       {
4.        int startPortRange=0;
5.        int stopPortRange=0;

6.        startPortRange = Integer.parseInt(args[0]);
7.        stopPortRange = Integer.parseInt(args[1]);



8.        for(int i=startPortRange; i <=stopPortRange; i++)
       {
9.                        try
                       {
10.                        Socket ServerSok = new Socket("127.0.0.1",i);

11.                 System.out.println("Port in use: " + i );

12.                        ServerSok.close();
                       }
13.                catch (Exception e)
                       {
                       }
14.        System.out.println("Port not in use: " + i );
       }
       }
}


Explanation Of The Code
Now I'm going to explain the code. First on line 4 and 5 I have declared a start and stop variable to hold the start and stop port numbers. Line 6 and 7 simply converts a string number into an integer number using the parseInt() method.

On line 8 we have a For loop, this loop uses the startPortRange variable to initialize the For loop. The loop increments until it reaches the stopPortRange. On line 9 we have a Try block, each time the For loop increments the Try block gets invoked.

The Try block creates an instance of the Socket Class. In the constructor of the Socket instance Class, we supply the hostname or IP address and the port number. The following code on line 10 creates an instance of the Socket Class with the localhost IP address. The variable "i" is the current port number.


Socket ServerSok = new Socket("127.0.0.1",i);


If a connection is made on the localhost with the current port number the Try block will print a "Port in use" message. If a connection could not be made on the localhost with the current port number, then "Port not in use" message will be printed to the console. On line 12 we close the Socket connection using the close() method.

We are now at the end of this article. I have very briefly introduced you to the java.net package and the Socket class. Author's url: http://www.cy2online.net


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(14)


1. View Comment

Sorry dude! when i am trying to compile your program one error is shown:exception in thread "main" java.lang.ArrayIndexoutofBoundException:0........why???????

View Tutorial          By: Avijit M. at 2007-09-14 00:43:55
2. View Comment

You have to run the compiled PortScanner with two arguments
java PortScanner 130 140
for example


View Tutorial          By: KRook at 2009-10-15 04:11:53
3. View Comment

Hello, I have executed the above code and it works but there is one problem with the code the port which it shows in use is again shown as not in use on the next line of the output please put the statement 'System.out.println("port not in use"+i)' in the catch block

View Tutorial          By: Sana at 2010-02-01 03:49:44
4. View Comment

Hello, I have executed the above code and it works but there is one problem with the code the port which it shows in use is again shown as not in use on the next line of the output please put the statement 'System.out.println("port not in use"+i)' in the catch block

View Tutorial          By: Sana at 2010-02-01 03:50:18
5. View Comment

Hi, thanks for your code, I have modified a little bit to scan a single port in different ip addresses, but when the ip doesn't exist it takes some time while it tries to get an answer, do you know if there is a way to reduce the response time? so that it doesnt take so long?

View Tutorial          By: Armando at 2010-08-10 09:34:35
6. View Comment

is there any port filter/block api for java?

View Tutorial          By: edwin at 2010-08-12 03:16:44
7. View Comment

Your code is syntactically correct, but semantically wrong.
You have to put the output statement within the catch blocks!

for(int i=startPortRange; i <=stopPortRange; i++)
{
try
{
Socket ServerSok = new Socket("127.0.0.1",i);
System.out.println("Port in use: " + i );
ServerSok.close();
}
catch (Exception e)
{ System.out.println( "Port" + i + "Not in Use");}

}


View Tutorial          By: mobinga at 2011-07-25 15:08:27
8. View Comment

Hai all, there is som question plzzzz help me
before that, im not so talented with java...

1. How i can add nw traffic analyser to my java project??
that means i would like to setup a nw utility graph to my javaSE project.
here its i hav used jpcap only...
2. How i can use JMap? plz help me...... i need to submitt my project on 23rd sept 2010.. thanks in advance plzzzzzz help me


View Tutorial          By: chandra at 2011-10-12 09:07:39
9. View Comment

when i am trying to compile your program one error is shown:exception in thread "main" java.lang.ArrayIndexoutofBoundException:0........why???????

anindya


View Tutorial          By: anindya at 2011-11-23 03:00:49
10. View Comment

Small modification.
System.out.println("Port not in use: " + i ); should be INSIDE the catch block. Otherwise, the output is like:

Port not in use: 79
Port in use: 80
Port not in use: 80
Port not in use: 81

Even if a Port is in use, it will print that its not in use.

Modified output

Port not in use: 79
Port in use: 80
Port not in use: 81
Port not in use: 82


View Tutorial          By: Rohit at 2012-02-07 16:22:52
11. View Comment

i have a error while i running this program
error is :class name,'PortScanner' , are only accepted if annotation processing is explicitly requested.........
plz help me to solve this error.....


View Tutorial          By: parul at 2012-02-08 15:40:09
12. View Comment

@ parul : check whether your are passing class file to the compiler for e.g. javac PortScanner

View Tutorial          By: heramb at 2012-03-28 07:15:21
13. View Comment

Error...!!
please send correct java code for port scanning,completing project for 7th sem
mayurii115@gmail.com


View Tutorial          By: mayuri at 2013-10-20 13:26:30
14. View Comment

Try this

import java.net.*;

public class PortScanner

{

public static void main(String args[])
{
int startPortRange=0;
int stopPortRange=0;

startPortRange = Integer.parseInt(args[0]);
stopPortRange = Integer.parseInt(args[1]);



for(int i=startPortRange; i <=stopPortRange; i++)
{
try
{
Socket ServerSok = new Socket("127.0.0.1",i);

System.out.println("Port in use: " + i );

ServerSok.close();
}
catch (Exception e)
{
}
System.out.println("Port not in use: " + i );
}
}
}


View Tutorial          By: Asad at 2014-02-13 05:55:26

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Syed M Hussain
How To Connect To A MySql Database in VB.net
Simple Port Scanner application using Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
The Basic Structure of a Simple Java program
Recursion in java
Abstract classes in Java
Text to Speech conversion program in Java
Read from a COM port using Java program
Vector example in Java
Connect to a password protected URL from Java program
Student marks calculation program in Java
Integer: byte, short, int, and long data types in Java
wait(), notify() and notifyAll() in Java - A tutorial
Increment and Decrement Operator
XML and Java - Parsing XML using Java Tutorial
Count number of vowels, consonants and digits in a String in Java
Calculate gross salary in Java
Most Emailed Articles (in Java)
TreeMap example in Java
Integer: byte, short, int, and long data types in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java program to print prime numbers using Thread
Bubble Sort in Java
emulator 0 terminated while waiting for it to register!
Java program for Map
History of Java
Creating Users and Passwords with Tomcat using tomcat-users.xml
What is a report design in JasperReports?
What is UTF-8?
java.lang.reflect package
CharSequence Interface in Java
The if-then-else Statement in Java