[英]Is there a way to get the MAC address of a device on a network based on its IP address? (C# & Android)
我有一個使用 C# 為 Android 制作的應用程序,它通過 ping 搜索本地網絡上連接的所有設備。
使用存在響應的 IP,我得到每個設備的主機名,如下所示:
private string GetHostName(string ipAddress)
{
try
{
IPHostEntry entry = Dns.GetHostEntry(ipAddress);
if (entry != null)
{
return entry.HostName;
}
}
catch (SocketException)
{
return "n/n";
}
return "";
}
我還需要從 IP 地址獲取 MAC 地址。 對於 android (Xamarin),我在 C# 中找不到示例
有沒有辦法做到這一點?
更新:
在對該問題的第一條評論中,有人提供了指向類似主題的鏈接。
解決方案是下一個:
public string GetMacByIP(string ipAddress)
{
try
{
// grab all online interfaces
var query = NetworkInterface.GetAllNetworkInterfaces()
.Where(n =>
n.OperationalStatus == OperationalStatus.Up && // only grabbing what's online
n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
.Select(_ => new
{
PhysicalAddress = _.GetPhysicalAddress(),
IPProperties = _.GetIPProperties(),
});
// grab the first interface that has a unicast address that matches your search string
var mac = query
.Where(q => q.IPProperties.UnicastAddresses
.Any(ua => ua.Address.ToString() == ipAddress))
.FirstOrDefault()
.PhysicalAddress;
// return the mac address with formatting (eg "00-00-00-00-00-00")
return String.Join("-", mac.GetAddressBytes().Select(b => b.ToString("X2")));
}
catch (Exception ex)
{
return ex.Message;
}
}
但它僅適用於進行查詢的設備,對於所有其他設備,在 v ar mac = query.Where(q => q.IPProperties.UnicastAddresses中引發異常並且錯誤是:'未設置對象引用到 object 的實例
沒有嘗試和捕捉:
感謝@Charlieface的建議, Permission Denied for access /proc/net/arp ARP table in Android 10我寫了以下代碼:
public static PhysicalAddress Lookup(IPAddress ip)
{
var runtime = Java.Lang.Runtime.GetRuntime();
var proc = runtime.Exec("ip neigh show");
proc.WaitFor();
var x = new Java.IO.InputStreamReader(proc.InputStream);
var reader = new Java.IO.BufferedReader(x);
String line;
while ((line = reader.ReadLine()) != null)
{
String[] clientInfo = line.Split(" +");
//if (!clientInfo[3].equalsIgnoreCase("type"))
//{
// String mac = clientInfo[3];
// String ip = clientInfo[0];
// //textView.append("\n\nip: " + ip + " Mac: " + mac);
// //Log.d("IP : ", ip);
// //Log.d("Mac : ", mac);
//}
}
}
它仍然需要改進,但它已經是一個很大的進步:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.