Reputation: 21
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);
}
}
}
}
Upvotes: 2
Views: 154
Reputation: 580
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.
Upvotes: 2
Reputation: 311045
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.
Upvotes: 0