通过IP获取设备的MAC地址

时间:2018-09-06 15:03:04

标签: java android

好吧,在我的应用程序中,我使用一些代码来发现本地网络中所有可访问的设备。 现在我想使用本地IP地址获取设备的Mac地址

我想要这样的东西:getMacAddress("192.168.1.23")

public static String getMacAddress(String ip)
{
    String macAddress = ...
    return macAddress;
}

我已经找到了这个,但是我不确定是否可以在局域网中的每台设备上使用它,如果可以,我将如何使用自定义IP地址使用它?

 WifiManager manager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
 WifiInfo info = manager.getConnectionInfo();
 String address = info.getMacAddress();

3 个答案:

答案 0 :(得分:2)

/proc/net/arp是本地ARP缓存,至少具有缓存的条目(可能是脱机的)。

protected String getMacAddress(String ipAddress) {
    try {
        BufferedReader br = new BufferedReader(new FileReader(new File("/proc/net/arp")));
        String line;
        while((line = br.readLine()) != null) {
            if(line.contains(ipAddress)) {
                /* this string still would need to be sanitized */
                return line;
            }
        }
        System.out.println(output);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

或者,可以扫描整个本地网段-

或从本地网络路由器检索ARP缓存。

答案 1 :(得分:2)

参考:How can I get the number of devices connected through the phones access-point?

您可以算出接入点上的已连接设备,并且它在android上的以下链接上具有硬件mac地址:http://www.flattermann.net/2011/02/android-howto-find-the-hardware-mac-address-of-a-remote-host/

上面链接的代码:

RowLeave(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs)
  

或者如果您在代码方面遇到问题,请尝试以下代码:

Class MainForm
' The form contains a DataGridView and btnQuit (and other buttons)

Private Sub dgv_RowLeave(ByVal sender As Object, ByVal e As DataGridViewCellEventArgs) Handles dgv.RowLeave

  ProgrammaticallyDoRowValidation(dgv.CurrentRow.Index) ' This does validation and more. 
  ' But if btnQuit is clicked, I need to know here, or before RowLeave is
  ' triggered and NOT do this row validation.
  ' ...
End Sub

Private Sub Form_Click(sender As Object, e As EventArgs) Handles MyBase.Click
  Dim frm As Form
  frm = CType(sender, Form)
  ' Translated from Sach's comment below. Code never reaches this event
  '(RowLeave prevents it).
End Sub

Private Sub Quit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnQuit.MouseClick

  QuitPgm() ' Contains some more stuff.
  ' Also never executed, because RowLeave is handled first.

End Sub
End Class

答案 2 :(得分:0)

该功能仅可用于获取您自己的MAC,即使那样,它在现代Android上也有严格的限制。您想要的不是Android的功能。