C#プログラムがMACアドレスを読み出す5つの方法
12230 ワード
public class GetMac
{
///<summary>
/// ipconfig /all Mac
///</summary>
///<returns></returns>
public static List<string> GetMacByIpConfig()
{
List<string> macs =new List<string>();
ProcessStartInfo startInfo = new ProcessStartInfo("ipconfig", "/all");
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;
Process p = Process.Start(startInfo);
//
StreamReader reader = p.StandardOutput;
string line = reader.ReadLine();
while (!reader.EndOfStream)
{
if (!string.IsNullOrEmpty(line))
{
line = line.Trim();
if (line.StartsWith(" "))
{
macs.Add(line.Substring(32));
}
}
line = reader.ReadLine();
}
//
p.WaitForExit();
p.Close();
reader.Close();
return macs;
}
///<summary>
/// WMI MAC
///</summary>
///<returns></returns>
public static List<string> GetMacByWmi()
{
List<string> macs =new List<string>();
string mac ="";
ManagementClass mc =new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"])
{
mac = mo["MacAddress"].ToString();
macs.Add(mac);
}
}
return macs;
}
///<summary>
/// NetworkInterface Mac
///</summary>
///<returns></returns>
public static List<string> GetMacByNetworkInterface()
{
List<string> macs =new List<string>();
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface ni in interfaces)
{
macs.Add(ni.GetPhysicalAddress().ToString());
}
return macs;
}
///<summary>
/// SendARP Mac
/// ( )
///</summary>
///<param name="remoteIP"></param>
///<returns></returns>
public static string GetMacBySendArp(string remoteIP)
{
StringBuilder macAddress =new StringBuilder();
try
{
Int32 remote = inet_addr(remoteIP);
Int64 macInfo =new Int64();
Int32 length =6;
SendARP(remote, 0, ref macInfo, ref length);
string temp = Convert.ToString(macInfo, 16).PadLeft(12, '0').ToUpper();
int x =12;
for (int i =0; i <6; i++)
{
if (i ==5)
{
macAddress.Append(temp.Substring(x -2, 2));
}
else
{
macAddress.Append(temp.Substring(x -2, 2) +"-");
}
x -=2;
}
return macAddress.ToString();
}
catch
{
return macAddress.ToString();
}
}
[DllImport("Iphlpapi.dll")]
private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
[DllImport("Ws2_32.dll")]
private static extern Int32 inet_addr(string ip);
}
ブログhttp://www.cnblogs.com/diulela/archive/2012/04/07/2436111.htmlより