在我的C#应用程序中,我希望使用NetworkInterface
类获取我的MAC地址,如下所示:
NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()
{
mac = nic.GetPhysicalAddress()
}
但是此代码返回没有':'的MAC或任何其他分隔符。
如何以这种格式检索MAC:
88:88:88:88:87:88
仅使用上面的代码?
答案 0 :(得分:29)
试
mac = string.Join (":", (from z in nic.GetPhysicalAddress().GetAddressBytes() select z.ToString ("X2")).ToArray());
答案 1 :(得分:2)
该命令的帮助显示了一种方式:
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.physicaladdress.aspx
PhysicalAddress address = adapter.GetPhysicalAddress();
byte[] bytes = address.GetAddressBytes();
for(int i = 0; i< bytes.Length; i++)
{
// Display the physical address in hexadecimal.
Console.Write("{0}", bytes[i].ToString("X2"));
// Insert a hyphen after each byte, unless we are at the end of the
// address.
if (i != bytes.Length -1)
{
Console.Write("-");
}
}
Console.WriteLine();
答案 2 :(得分:2)
使用comment by eFloh使用BitConverter我能够执行以下操作(假设mac
已预先定义为字符串)。
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
mac = BitConverter.ToString(nic.GetPhysicalAddress().GetAddressBytes()).Replace('-', ':');
//Do whatever else necessary with each mac...
}
答案 3 :(得分:1)
你想要表明的是,你必须这样做:
txtMac.text=getFormatMac(GetMacAddress());
public string GetMacAddress()
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
if (sMacAddress == String.Empty)// solo retorna la mac de la primera tarjeta
{
IPInterfaceProperties properties = adapter.GetIPProperties();
sMacAddress = adapter.GetPhysicalAddress().ToString();
}
}
return sMacAddress;
}
public string getFormatMac(string sMacAddress)
{
string MACwithColons = "";
for (int i = 0; i < macName.Length; i++)
{
MACwithColons = MACwithColons + macName.Substring(i, 2) + ":";
i++;
}
MACwithColons = MACwithColons.Substring(0, MACwithColons.Length - 1);
return MACwithColons;
}
答案 4 :(得分:0)
尝试这样的事情:
// Insert Colons on MAC
string MACwithColons = "";
for (int i = 0; i < MAC.Length; i++) {
MACwithColons = MACwithColons + MAC.Substring(i, 2) + ":";
i++;
}
MACwithColons = MACwithColons.Substring(0, MACwithColons.Length - 1); // Remove the last colon