【问题标题】:How to query connected device IP addresses on LAN如何查询局域网内连接的设备IP地址
【发布时间】:2017-10-25 00:05:07
【问题描述】:

我正在编写一个应用程序,它应该扫描局域网以查找连接的设备,并返回连接设备的 IP 地址。

我的扫描仪包括“ping”一个 IP 地址范围内的每个 IP。这个固定一系列 IP 地址的过程非常耗时。

然后我了解到在 Windows 机器上有一个叫做 ARP(地址解析协议)缓存的东西,它基本上是一个有效 IP 地址的列表,或者连接设备的 IP 地址。

既然 Android 不是 Windows,有没有办法简单地使用 API 或其他东西来访问类似的表?

Tl;Dr 如何在 Android 中查询网络上的有效 IP 地址(而不是 ping 它们)

【问题讨论】:

    标签: android


    【解决方案1】:

    到目前为止我想出的最佳解决方案是在文件路径/proc/net/arp 处读取 Android 设备中的 ARP 文件

    这是应用程序的主要活动类,它在简单的文本视图中显示文件内容

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
    
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            TextView tv = (TextView) findViewById(R.id.textView);
    
            // Get an array list of mac to IP address mapping
            ArrayList<String> arpTableLines = getArpTableLines();
    
            // Generate a string to display in the text view based on the mapping
            String textViewText = getTextViewText(arpTableLines);
    
            // Set the text view value
            tv.setText(textViewText);
        }
    
        public ArrayList<String> getArpTableLines(){
    
            ArrayList<String> lines = new ArrayList<>();
    
            try{
    
                String line = "";
    
                BufferedReader localBufferdReader =
                        new BufferedReader(new FileReader(new File("/proc/net/arp")));
    
                while ((line = localBufferdReader.readLine()) != null) {
                    String[] ipmac = line.split("[ ]+");
                    if (!ipmac[0].matches("IP")) {
                        String ip = ipmac[0];
                        String mac = ipmac[3];
                        lines.add(ip + " <~> " + mac);
                    }
                }
    
            }catch (FileNotFoundException ex){
                Log.v("TAG",Log.getStackTraceString(ex));
            } catch (IOException ex){
                Log.v("TAG",Log.getStackTraceString(ex));
            }
    
            return lines;
        }
    
        public String getTextViewText(ArrayList<String> lines){
            String result = "";
            for(String line : lines) result += line + "\n";
            return result;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-06
      • 2011-09-01
      • 2020-10-28
      • 2015-03-22
      • 1970-01-01
      • 2021-07-08
      • 2019-05-02
      • 1970-01-01
      • 2019-11-04
      相关资源
      最近更新 更多