views:

66

answers:

2
import java.net.*;

import java.io.IOException;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class PortScanner {

     public static void main(String[] args) {
     InetAddress ia=null;
     String host=null;
         try {

         host=JOptionPane.showInputDialog("Enter the Host name to scan:\n example: xxx.com");
             if(host!=null){
             ia = InetAddress.getByName(host);
         scan(ia); }
     }
         catch (UnknownHostException e) {
         System.err.println(e );
     }
     System.out.println("Bye from NFS");
     //System.exit(0);
 }

    public static void scan(final InetAddress remote) {
    //variables for menu bar

    int port=0;
    String hostname = remote.getHostName();

         for ( port = 70; port < 65536; port++) {
             try {
             Socket s = new Socket(remote,port);
             System.out.println("Server is listening on port " + port+ " of " + hostname);
             s.close();
             break;
         }
             catch (IOException ex) {
             // The remote host is not listening on this port
             System.out.println("Server is not listening on port " + port+ " of " + hostname);
         }
     }//for ends
 }
}

please help me.

+3  A: 

I am not sure if this will speed things up, but since each socket your making is independent of the next socket, have you tried making more threads so that you can create new sockets when older sockets are waiting for their handshake to complete.

Andrew Keith
i mean is this set of code for ( port = 70; port < 65536; port++) { try { Socket s = new Socket(remote,port); System.out.println("Server is listening on port " + port+ " of " + hostname); s.close(); break; } can it be processed faster? cause it took much time to scan the port one by one.
Otip88
The processing time is not going to increase much because a network connection handshake performance is mostly out of your control. You might have better performance just trying to open sockets in parallel instead of waiting for each to complete in serial.
Andrew Keith
Ok...thank's for your tips.. cheers mate.
Otip88
A: 

Instead of using the line

Socket s = new Socket(remote,port);

You should use

Socket s = new Socket();
int timeout = 100; // milliseconds
s.connect( new InetSocketAddress( remote, port ), timeout );

This way you won't have to wait for the default TCP timeout to see that this port is blocked by a firewall without any response.

tangens
This will fail as soon as it takes more than 100 milliseconds to establish a connection.
Bombe
Yes, that's the idea. Of course you will adjust this value to the given infrastructure. But if you try to connect without timeout, you will wait some minutes until you fail (if a firewall blocks this port).
tangens