2

I am designing a port scanner to detect which ports are in use. The problem is it shows all ports as not in use, even though i know some of them are being used. Need help identifying the problem. Here's my code.


package portscanner;

import java.net.Socket;
import java.util.Scanner;

/**
 *
 * @author DeLL
 */
public class Main {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    System.out.println("Enter the range of ports to be scanned:");
    Scanner ob=new Scanner(System.in);
    int start=ob.nextInt();
    int stop=ob.nextInt();
    if(start<0||stop<0||start>65535||stop>65535){
        System.out.println("Invalid Range!!!");
    }
    for(int i=start;i<=stop;i++){
        try{
            Socket sock = new Socket("127.0.0.1",i);
            System.out.println("Port in use :"+i);
            sock.close();
        }
        catch(Exception e){
            System.out.println("Port not in use: "+i);
        }
    }
}

}

2
  • Hmm. Works for me. It tells me port 22 (ssh), 1090, and a couple of other ones are in use. Commented Jun 27, 2012 at 9:04
  • 1
    Is any firewall active during tests? Firewalls usually make rules for java launcher (i.e. 'java.exe'). It is common to all java programs and may be blacklisted for some reason earlier. Commented Jun 27, 2012 at 9:10

2 Answers 2

2

Looking there: http://docs.oracle.com/javase/6/docs/api/java/net/Socket.html#Socket%28java.lang.String,%20int%29

the Socket constructor throws three exceptions:
UnknownHostException - if the IP address of the host could not be determined.
IOException - if an I/O error occurs when creating the socket.
SecurityException - if a security manager exists and its checkConnect method doesn't allow the operation.

None of them is throws when the port is already in use. You can try using the bind() method, that throws an IOException if the socket is alredy bound.

Sign up to request clarification or add additional context in comments.

1 Comment

Assuming the OP's code is intended to be used for both local and remote machines, when connecting to a host, an IOException should be thrown when no service is listening for connections. If no service is listening on a port, then the port is not in use. For just scanning the local machine, bind() would be a good test. I'd be willing to bet that OP's problem is a firewall issue.
0

You're too indiscriminate with your exception handling. Only ConnectException really tells you the port isn't in use. All the other exceptions indicate a different problem. Catch and handle ConnectException separately.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.