0

I am trying to make a app that scans all the ip in range for a specific open port (5050) and if it is open write some message on LOG.

heres the code :

public void run(){
        for(int i=0;i<256;i++)
        {
            Log.d("NetworkScanner","attemping to contact 192.168.1."+i);
            try {
                Socket socket=new Socket(searchIP+i,5050);
                possibleClients.add(searchIP);
                socket.close();

                Log.d("NetworkScanner"," 192.168.1."+i+" YEAAAHHH");

            } catch (UnknownHostException e) {

                Log.d("NetworkScanner"," 192.168.1."+i+" unavailable");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

EDIT: here's a new problem: Even if a host is found online without the port open the scanning process (for loop) is stuck for a long time before moving to next. also scanning each host is taking considerable time!

Phew the final solution was to make a Socket object with default constructor then create the InetAddr object for the host and then use the Connect(InetAddr,timeout) function of the socket api with timeout in milliseconds (approx 300ms) that scans every ip in just 300 ms or less (less than 200 ms may give errors) and multi threading to scan in parallel make it as fast as 5 sec to scan all the IPs in range..

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Allahjane
  • 1,920
  • 3
  • 24
  • 42
  • Phew the final solution was to make a Socket object with default constructor then create the InetAddr object for the host and then use the Connect(InetAddr,timeout) funtion of the socket api with timeout in milliseconds (approx 300ms) that scans every ip in just 300 ms or less (less than 200 ms may give errors) and multi threading to scan in parallel make it as fast as 5 sec to scan all the IPs in range.. Thanks to everyone for their replies – Allahjane Apr 25 '13 at 08:32

2 Answers2

2

You are breaking out of the loop when no Exception is thrown.

You need to remove break;


To address your new problem:

Of course it's slow. What did you expect? You are trying to establish a connection to each IP in your subnet which takes time. It seems you are only trying figure out what devices are available on the network, so you might be able to decrease the time a little by looking at this answer. He is using the build in isReachable method which accepts a timeout value. It will still take some time, but not that much time.

Community
  • 1
  • 1
MAV
  • 7,260
  • 4
  • 30
  • 47
  • Yes, your answer helped but there is still some issue, (see the edit) if i accept this one now the question will get flagged as solved. I will accept as soon as it is solved – Allahjane Apr 03 '13 at 17:08
  • See i started the scan since your first answer and it still hasn't crossed 192.168.1.190! – Allahjane Apr 03 '13 at 17:10
0

Remove the "break;"...it stops the iteration.

dimi
  • 1,496
  • 2
  • 15
  • 27