java - 以编程方式发现本地网络设备和 IO

标签 java android multithreading networking ip

我正在尝试制作一个项目,必须使我能够在同一网络中找到本地设备以及有关其 IP、MAC 地址和供应商的信息。到目前为止一切都很好,但问题是我意识到通过这段代码,它只能发现移动电话,并且以某种方式看不到我的笔记本电脑?我测试了这段代码,它只显示我的平板电脑和手机,但没有电脑。如果您有任何建议,请现在就告诉我。提前致谢。这是我的代码,亲爱的。

//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;
}

}

这是我的另一个类,我在其中处理要执行的线程

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;
    }
}

}

最佳答案

像在命令行上一样执行此 ping,也许您可​​以更改编码风格。

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();
}

关于java - 以编程方式发现本地网络设备和 IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35646666/

相关文章:

java - 如何在 Java 上使用 Maven 按顺序运行具有多个 testng 测试的多个类

java - 使用faceId/touchId的应用程序的安全性?它是如何工作的?

android - 如何获得预定义的振动模式?

android - Gradle离线同步问题

android - 检测到堆栈损坏,dalvik VM 崩溃

swift - 我可以安全地将 NSManagedObject 传递给 performBackgroundTask 吗?

ruby - `threadsafe!` rails 中缺少方法

java - Spark Hbase : How to convert a dataframe to Hbase org. apache.hadoop.hbase.client.Result

java - 在单独的循环上提取draw()方法(PApplet作为JADE代理)

java - 克隆一个 int[] ——有人有更快的建议吗?