简体   繁体   中英

Host scanning on a private network

I'm trying to list down all available devices on a local WiFi network. To do this I'm using simple ICMP echo technique to check if a device is connected or not. The problem is the time it takes to scan the entire subnet. I'm using 7 ms wait time between subsequent scan. My question is, can I use Java multi threading for this purpose where each thread would work independently to scan different segments? Would there be any link-layer constraints? Thanks for your help!

I wrote something a while ago that would scan a local network for all available devices and then scan each port to see if its open as well. That is available here .

Since it's a bit long, ill explain how I did it.

First create a class like so:

public class AddressWorker implements Runnable
{
    private String address;

    public AddressWorker(String address, Vector<String> validAddresses) { this.address = address; }

    public void run()
    {
        //Your existing code that uses ICMP to listen for a device
        //if the address responds add it to valid addresses
    }
}

Since runnables function similarly to threads we will use them as such.

Vector<String> allRespondedAddress = new Vector(256, 256);
ExecutorService addressExecutor = Executors.newCachedThreadPool();
while (list all ip addresses)
{
    addressExecutor.execute(new AddressWorker(nextAddress, allRespondedAddresses));
}

addressExecutor.awaitTermination(some time);

A CachedThreadPool will run every runnable added to it as a thread. It will automatically allocate and optimize resources (eg if one thread is waiting and another behind it needs to do work it will move the workable thread ahead while the other(s) wait). On my cpu it scans all 256 addresses on the subnet and all 65536 ports per address in about 30 seconds. I felt my full code was a bit too long to post here, but its all very accessible and commented on the link i posted. I'm not a networker so I'm afraid I can't help you with link-layer constraints as I do not know what they are.

I hope this gets you looking in the right direction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM