【发布时间】:2022-01-18 03:23:03
【问题描述】:
我有一个用 C# for 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 地址。我在 C# for android (Xamarin) 中找不到示例
有办法吗?
更新:
在对该问题的第一条评论中,有人提供了一个类似主题的链接。
解决办法是下一个:
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;
}
}
但是它只适用于进行查询的设备,对于所有其他设备,var mac = query 中会引发异常 .Where(q => q.IPProperties.UnicastAddresses 并且错误是:'对象引用未设置为对象的实例
没有尝试和捕捉:
【问题讨论】:
-
我到了那个例子,在 var mac = query.Where (q => q.IPProperties.UnicastAddresses, etc etc 等发生异常: System.NullReferenceException: '对象引用未设置为一个对象。'在我看来,这个例子只适用于 PC。
-
@Jason 我尝试并确定是否所有 IP 都会出现此问题,并且对于某些地址获得了 MAC,而对于其他地址则没有。
-
请注意。在更高版本的Android中,它将随机化mac地址
-
见stackoverflow.com/questions/62550498/…你真的需要提高你的谷歌搜索技能,我会在大约 30 秒内找到这些
标签: c# android xamarin xamarin.android