我想获取主适配器的物理地址。
首先,我在下面的脚本中得到了机器的LocaIpAddress,然后我试图将这个本地IP与所有网络适配器的IP进行比较,找出哪一个是主适配器,然后得到它的物理地址。
public static string GetLocalIPAddress()
{
var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new System.Exception("No network adapters with an IPv4 address in the system!");
}
接下来我想做的是把这个本地IP和所有网络适配器的IP进行比较,找出哪个是主适配器,然后得到它的物理地址。 在下面的脚本中,问题是:
PhysicalAddress physicalAddress;
void GetNetworkInterfacesWin()
{
GetExternalIp();
IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
UnicastIPAddressInformationCollection ipList = adapter.GetIPProperties().UnicastAddresses;
foreach(UnicastIPAddressInformation uipai in ipList)
{
if(uipai.Address.ToString() == GetLocalIPAddress())
{
physicalAddress = adapter.GetPhysicalAddress();
print(physicalAddress);
print(uipai.Address.ToString());
break;
}
}
byte[] bytes = physicalAddress.GetAddressBytes();
string mac = null;
for (int i = 0; i < bytes.Length; i++)
{
mac = string.Concat(mac + (string.Format("{0}", bytes[i].ToString("X2"))));
if (i != bytes.Length - 1)
{
mac = string.Concat(mac + "-");
}
}
info += mac + "\n";
info += "\n";
}
debugtext.text = info;
Debug.Log(info);
}
问题是...physicalAddress = adapter.GetPhysicalAddress();
值返回一个空字符串,因此。debugtext.text = info; Debug.Log(info);
最后是""。
如果有其他的变通方法,可以忽略虚拟适配器,得到连接的和活动的适配器的物理地址,我非常感谢你的分享。
我发现一个更简单的方法在windows上,所以任何人都想知道。
void GetNetworkInterfaces()
{
string physicalAddress = "";
NetworkInterface[] nice = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adaper in nice)
{
IPInterfaceProperties properties = adaper.GetIPProperties();
if (properties.DnsSuffix.Contains("lan"))
{
physicalAddress = adaper.GetPhysicalAddress().ToString();
macAddress = physicalAddress;
break;
}
}
}
显然物理适配器的后缀是 lan
.你可以用它来检查是否是实物。