David
David

Reputation: 4117

How to discover Ip Addresses where listening on port x

I would like to scan the IP range from my subnet. I would like to save the IP addresses, which will be heard in on a specific port. I use this code:

        for (int host = 1; host < 255; host++) {
            String ip = networkAddress + host;

            Socket socket;
            try {
                socket = new Socket(ip, port);
                System.out.println(ip + "  +");
                serverList.add(ip);
                socket.close();
            }
            catch (Exception e) {
                System.out.println(ip + "  -");
            }
        }

But my problem is that it takes too much time ... Is there any faster way?

Upvotes: 0

Views: 350

Answers (2)

user207421
user207421

Reputation: 311055

Use new Socket() (no arguments) and then call Socket.connect() with a shortish timeout, say a few seconds.

Upvotes: 0

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340993

Use multithteading. Since most of the time is actually spent waiting for a response, you can safely create 100 (or even 200) threads, reducing the total time by two orders of magnitude. Use Executors class to create a thread pool and submit one task per each host.

Remember that the serverList collection will then have to be thread safe. Use shutdown() and awaitTermination() pair to wait for results. Alternatively use CompletionService to collect results as they arrive.

Upvotes: 1

Related Questions