MACAddress
Data type: string
Access type: Read-only
Media Access Control (MAC) address of the network adapter. A MAC address is assigned by the manufacturer to uniquely identify the network adapter.
Example: "00:80:C7:8F:6C:96"
如果你不熟悉 WMI API (Windows 管理规范) ,有一个针对.NET 应用程序的 很好的概述。
WMI 可以通过.Net 运行时在所有版本的窗口中使用。
下面是一个代码示例:
System.Management.ManagementClass mc = default(System.Management.ManagementClass);
ManagementObject mo = default(ManagementObject);
mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (var mo in moc) {
if (mo.Item("IPEnabled") == true) {
Adapter.Items.Add("MAC " + mo.Item("MacAddress").ToString());
}
}
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) {
if (nic.OperationalStatus == OperationalStatus.Up){
if (nic.Id == "yay!")
}
}
下面是一些 C # 代码,它返回第一个操作网络接口的 MAC 地址。假设 NetworkInterface程序集是在其他操作系统上使用的运行时(即 Mono)中实现的,那么这将在其他操作系统上起作用。
新版本: 以最快的速度返回具有有效 MAC 地址的 NIC。
/// <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;
}
原始版本: 只返回第一个。
/// <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;
}
我唯一不喜欢这种方法的是,如果你有像北电数据包小端口或某种类型的 VPN 连接,它有被选择的潜力。据我所知,没有办法区分实际物理设备的 MAC 和某种类型的虚拟网络接口。
var macAddr =
(
from nic in NetworkInterface.GetAllNetworkInterfaces()
where nic.OperationalStatus == OperationalStatus.Up
select nic.GetPhysicalAddress().ToString()
).FirstOrDefault();
public static string GetMACAddress()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true");
IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
string mac = (from o in objects orderby o["IPConnectionMetric"] select o["MACAddress"].ToString()).FirstOrDefault();
return mac;
}
或者在 Silverlight 中(需要更高的信任度) :
public static string GetMACAddress()
{
string mac = null;
if ((Application.Current.IsRunningOutOfBrowser) && (Application.Current.HasElevatedPermissions) && (AutomationFactory.IsAvailable))
{
dynamic sWbemLocator = AutomationFactory.CreateObject("WbemScripting.SWBemLocator");
dynamic sWbemServices = sWbemLocator.ConnectServer(".");
sWbemServices.Security_.ImpersonationLevel = 3; //impersonate
string query = "SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true";
dynamic results = sWbemServices.ExecQuery(query);
int mtu = int.MaxValue;
foreach (dynamic result in results)
{
if (result.IPConnectionMetric < mtu)
{
mtu = result.IPConnectionMetric;
mac = result.MACAddress;
}
}
}
return mac;
}
我真的很喜欢 AVee 的解决方案与最低的 IP 连接度量!但是如果安装了第二个具有相同指标的网卡,MAC 比较可能会失败..。
最好将接口的描述存储在 MAC 中。在以后的比较中,您可以通过这个字符串来识别正确的 nic。下面是一个示例代码:
public static string GetMacAndDescription()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true");
IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
string mac = (from o in objects orderby o["IPConnectionMetric"] select o["MACAddress"].ToString()).FirstOrDefault();
string description = (from o in objects orderby o["IPConnectionMetric"] select o["Description"].ToString()).FirstOrDefault();
return mac + ";" + description;
}
public static string GetMacByDescription( string description)
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true");
IEnumerable<ManagementObject> objects = searcher.Get().Cast<ManagementObject>();
string mac = (from o in objects where o["Description"].ToString() == description select o["MACAddress"].ToString()).FirstOrDefault();
return mac;
}
假设我有一个 TcpConnection,使用的是192.168.0.182的本地 ip。然后,如果我想知道那个 NIC 的 mac 地址,我会调用这个方法: GetMacAddressUsedByIp("192.168.0.182")
public static string GetMacAddressUsedByIp(string ipAddress)
{
var ips = new List<string>();
string output;
try
{
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = "ipconfig";
p.StartInfo.Arguments = "/all";
p.Start();
// Do not wait for the child process to exit before
// reading to the end of its redirected stream.
// p.WaitForExit();
// Read the output stream first and then wait.
output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
catch
{
return null;
}
// pattern to get all connections
var pattern = @"(?xis)
(?<Header>
(\r|\n) [^\r]+ : \r\n\r\n
)
(?<content>
.+? (?= ( (\r\n\r\n)|($)) )
)";
List<Match> matches = new List<Match>();
foreach (Match m in Regex.Matches(output, pattern))
matches.Add(m);
var connection = matches.Select(m => new
{
containsIp = m.Value.Contains(ipAddress),
containsPhysicalAddress = Regex.Match(m.Value, @"(?ix)Physical \s Address").Success,
content = m.Value
}).Where(x => x.containsIp && x.containsPhysicalAddress)
.Select(m => Regex.Match(m.content, @"(?ix) Physical \s address [^:]+ : \s* (?<Mac>[^\s]+)").Groups["Mac"].Value).FirstOrDefault();
return connection;
}
/// <summary>
/// returns the first MAC address from where is executed
/// </summary>
/// <param name="flagUpOnly">if sets returns only the nic on Up status</param>
/// <returns></returns>
public static string[] getOperationalMacAddresses(Boolean flagUpOnly)
{
string[] macAddresses = new string[NetworkInterface.GetAllNetworkInterfaces().Count()];
int i = 0;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up || !flagUpOnly)
{
macAddresses[i] += ByteToHex(nic.GetPhysicalAddress().GetAddressBytes());
//break;
i++;
}
}
return macAddresses;
}
/// <summary>
/// Get the MAC of the Netowrk Interface used to connect to the specified url.
/// </summary>
/// <param name="allowedURL">URL to connect to.</param>
/// <param name="port">The port to use. Default is 80.</param>
/// <returns></returns>
private static PhysicalAddress GetCurrentMAC(string allowedURL, int port = 80)
{
//create tcp client
var client = new TcpClient();
//start connection
client.Client.Connect(new IPEndPoint(Dns.GetHostAddresses(allowedURL)[0], port));
//wai while connection is established
while(!client.Connected)
{
Thread.Sleep(500);
}
//get the ip address from the connected endpoint
var ipAddress = ((IPEndPoint)client.Client.LocalEndPoint).Address;
//if the ip is ipv4 mapped to ipv6 then convert to ipv4
if(ipAddress.IsIPv4MappedToIPv6)
ipAddress = ipAddress.MapToIPv4();
Debug.WriteLine(ipAddress);
//disconnect the client and free the socket
client.Client.Disconnect(false);
//this will dispose the client and close the connection if needed
client.Close();
var allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
//return early if no network interfaces found
if(!(allNetworkInterfaces?.Length > 0))
return null;
foreach(var networkInterface in allNetworkInterfaces)
{
//get the unicast address of the network interface
var unicastAddresses = networkInterface.GetIPProperties().UnicastAddresses;
//skip if no unicast address found
if(!(unicastAddresses?.Count > 0))
continue;
//compare the unicast addresses to see
//if any match the ip address used to connect over the network
for(var i = 0; i < unicastAddresses.Count; i++)
{
var unicastAddress = unicastAddresses[i];
//this is unlikely but if it is null just skip
if(unicastAddress.Address == null)
continue;
var ipAddressToCompare = unicastAddress.Address;
Debug.WriteLine(ipAddressToCompare);
//if the ip is ipv4 mapped to ipv6 then convert to ipv4
if(ipAddressToCompare.IsIPv4MappedToIPv6)
ipAddressToCompare = ipAddressToCompare.MapToIPv4();
Debug.WriteLine(ipAddressToCompare);
//skip if the ip does not match
if(!ipAddressToCompare.Equals(ipAddress))
continue;
//return the mac address if the ip matches
return networkInterface.GetPhysicalAddress();
}
}
//not found so return null
return null;
}
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
PhysicalAddress Mac = nic.GetPhysicalAddress();
}
}