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?

有帮助吗?

解决方案

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.

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top