ecco qualche codice C# che restituisce l'indirizzo MAC della prima interfaccia di rete operativa. Supponendo che l'assembly NetworkInterface
sia implementato nel runtime (cioè Mono) utilizzato su altri sistemi operativi, ciò funzionerebbe su altri sistemi operativi.
Nuova versione: restituisce la scheda NIC con la velocità più veloce che ha anche un indirizzo MAC valido.
/// <summary>
/// Finds the MAC address of the NIC with maximum speed.
/// </summary>
/// <returns>The MAC address.</returns>
private string GetMacAddress()
{
const int MIN_MAC_ADDR_LENGTH = 12;
string macAddress = string.Empty;
long maxSpeed = -1;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
log.Debug(
"Found MAC Address: " + nic.GetPhysicalAddress() +
" Type: " + nic.NetworkInterfaceType);
string tempMac = nic.GetPhysicalAddress().ToString();
if (nic.Speed > maxSpeed &&
!string.IsNullOrEmpty(tempMac) &&
tempMac.Length >= MIN_MAC_ADDR_LENGTH)
{
log.Debug("New Max Speed = " + nic.Speed + ", MAC: " + tempMac);
maxSpeed = nic.Speed;
macAddress = tempMac;
}
}
return macAddress;
}
Versione originale: restituisce solo il primo.
/// <summary>
/// Finds the MAC address of the first operation NIC found.
/// </summary>
/// <returns>The MAC address.</returns>
private string GetMacAddress()
{
string macAddresses = string.Empty;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
macAddresses += nic.GetPhysicalAddress().ToString();
break;
}
}
return macAddresses;
}
L'unica cosa che non mi piace di questo approccio è se si dispone come un Nortel Packet Miniport o qualche tipo di connessione VPN ha il potenziale di essere scelti. Per quanto posso dire, non c'è modo di distinguere un MAC di un dispositivo fisico reale da un qualche tipo di interfaccia di rete virtuale.
Quando si dice attraverso SO, si intende tra diversi sistemi operativi Microsoft? –