在c#中格式化MAC地址
本文关键字:MAC 地址 格式化 | 更新日期: 2023-09-27 18:08:31
在我的c#应用程序中,我想通过使用NetworkInterface
类获得我的MAC地址,如下所示:
NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()
{
mac = nic.GetPhysicalAddress()
}
但是这段代码返回没有':'或任何其他分隔符的MAC。
如何以这种格式检索MAC:88:88:88:88:87:88
只使用上面的代码?
try
mac = string.Join (":", (from z in nic.GetPhysicalAddress().GetAddressBytes() select z.ToString ("X2")).ToArray());
该命令的帮助显示了一种方法:
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();
使用eFloh的注释使用BitConverter我能够做到以下(假设mac
是预定义为字符串)。
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
mac = BitConverter.ToString(nic.GetPhysicalAddress().GetAddressBytes()).Replace('-', ':');
//Do whatever else necessary with each mac...
}
试试这样:
// 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
在你想显示的地方,你必须这样做:
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;
}