views:

237

answers:

3

this is the code that i get so far...

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);
     }
    }
}

} for example on smtp server the system use port 25, and i need to scan port on remote client that connected to the smtp server. how can i do that?

please help me.

A: 

Firstly there are some methodological problems with this way of doing it since a port can be in use, but not listening.

If you're actually just looking for listening ports, and you want to use the approach above, at least spawn off some threads so that you don't have to wait for each port to time out sequentially.

The best way would be to mimic something like a syn scan rather than doing a full TCP handshake, but I'm not sure you can get that close to the metal in Java.

Neat question though.

Allain Lalonde
+2  A: 

Your code should look like this:

    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);
            }
    }
David Rabinowitz
that should do the minor problem...
Otip88
Was this your problem or is there something else?
David Rabinowitz
yep, theres something else. I need to know the port number on other computer that connected on my computer.
Otip88
+1  A: 

If I understood your problem:

  • a process S runs on machine A and listens on port P for incoming connections
  • a process C runs on machine B and connects from port T to P on A
  • your program F runs on machine A
  • F is not S

Do you want to discover T in F using Java? You cannot!

You have to read the operative system table of open sockets. This is an operative system dependent operation and it is not supported by java.

Otherwise if F is S, you can change the code of S to discover T. If S uses java.net.ServerSocket class, you can search ServerSocket.accept() and discover T using getPort() on the returned Socket instance.

LLP, Andrea

andcoz