简体   繁体   中英

Discovering Local Network Devices & IPs Programmaticaly

I'm trying to make a project that must make me able to find local devices in same network and information regarding their IPs,mac addresses and vendors.Everything is good so far but question is I relaized that by this code ,it only discovers to mobile phones and somehow doesnt see my laptops ? I tested this code and it only shows my tablet and phones but no computers.If u have any suggestion pls let me now.Thanks in advance.And here is my code belove.

//This class is my pinger class

public class DiscoverRunner implements Runnable {
private List<InetAddress> results;

private String subnet;
private Integer startAdd;
private Integer numAdds;

public DiscoverRunner(String subnet, Integer start, Integer steps) {
    this.subnet = subnet;
    this.startAdd = start;
    this.numAdds = steps;
    results = new LinkedList<InetAddress>();
}




@Override
public void run() {


    int timeout=4000;
       for (int i=startAdd;i<startAdd+numAdds;i++){

           String host=subnet +"." + i;
           try {
               InetAddress a = InetAddress.getByName(host);


            if (a.isReachable(timeout)){

                results.add(a);
                //System.out.println(host + " is reachable");
               }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       }

}

public List<InetAddress> getResults(){
    return results;
}

}

And here is my another class where i Handle threads to execute

public class Pinger {

private static final int NUMTHREADS = 254;
public static String myMacAddress = "";

public static ArrayList<Device> getDevicesOnNetwork(String subnet) throws IOException {
    LinkedList<InetAddress> resAddresses = new LinkedList<InetAddress>();
    DiscoverRunner[] tasks = new DiscoverRunner[NUMTHREADS];

    Thread[] threads = new Thread[NUMTHREADS];


    //Create Tasks and treads
    for (int i = 0; i < NUMTHREADS; i++) {
        tasks[i] = new DiscoverRunner(subnet,i,1);
        threads[i] = new Thread(tasks[i]);
    }
    //Starts threads
    for (int i = 0; i < NUMTHREADS; i++) {
        threads[i].start();
    }

    for (int i = 0; i < NUMTHREADS; i++) {
        try {
            threads[i].join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    for (int i = 0; i < NUMTHREADS; i++) {
        for (InetAddress a : tasks[i].getResults()) {
            try {
                a = InetAddress.getByName(a.getHostAddress());

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            resAddresses.add(a);
        }

    }

    ArrayList<Device> foundDev = new ArrayList<Device>(resAddresses.size());


    for (InetAddress a : resAddresses) {
        foundDev.add(new Device(a.getHostAddress(), getMacFromArpCache(a.getHostAddress()), a.getCanonicalHostName(), getVendorName(getMacFromArpCache(a.getHostAddress()))));
    }


    return foundDev;
}

/**
 * Try to extract a hardware MAC address from a given IP address using the
 * ARP cache (/proc/net/arp).<br>
 * <br>
 * We assume that the file has this structure:<br>
 * <br>
 * IP address       HW type     Flags       HW address            Mask     Device
 * 192.168.18.11    0x1         0x2         00:04:20:06:55:1a     *        eth0
 * 192.168.18.36    0x1         0x2         00:22:43:ab:2a:5b     *        eth0
 *
 * @param ip
 * @return the MAC from the ARP cache
 */
public static String getMacFromArpCache(String ip) {


    if (ip == null) {
        return null;
    }

    BufferedReader br = null;

    try {


        br = new BufferedReader(new FileReader("/proc/net/arp"));

        String line;
        while ((line = br.readLine()) != null) {
            String[] splitted = line.split(" +");


            if (splitted != null && splitted.length >= 4 && ip.equals(splitted[0])) {
                // Basic sanity check
                String mac = splitted[3];

                if (mac.matches("..:..:..:..:..:..")) {
                    return mac;

                } else {
                    return null;

                }
            }


        }
        return myMacAddress;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) {
                br.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}


public static String getVendorName(String MacAddress) throws IOException {

    try {
        URL url = new URL("http://api.macvendors.com/" + MacAddress);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");

        InputStream in = new BufferedInputStream(conn.getInputStream());
        String vendorName = org.apache.commons.io.IOUtils.toString(in, "UTF-8");


        return vendorName;
    } catch (MalformedURLException e) {


        return null;
    } catch (ProtocolException e) {

        return null;
    } catch (IOException e) {

        return null;
    }
}

}

this ping as you do on command line, maybe you can change your coding style.

try {
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec("ping 192.168.0.142");

        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line;
        while ((line = input.readLine()) != null) {
            System.out.println(line);
            p.destroy();
            break;
        }
        input.close();
} catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
}

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