C#實(shí)現(xiàn)自動(dòng)獲取電腦MAC地址
自動(dòng)獲取電腦MAC地址
完整代碼
/// <summary>
/// 獲取電腦MAC地址
/// </summary>
/// <returns></returns>
public static List<string> GetMacByWmi()
{
string key = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\";
List<string> macList = new List<string>();
try
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet && adapter.GetPhysicalAddress().ToString().Length != 0)
{
string fRegistryKey = key + adapter.Id + "\\Connection";
RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false);
if (rk != null)
{
//string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString();
//if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI")
{
string macAddress = adapter.GetPhysicalAddress().ToString();
for (int i = 1; i < 6; i++)
{
macAddress = macAddress.Insert(3 * i - 1, "-");
}
macList.Add(macAddress);
//break;
}
}
}
}
}
catch (Exception ex)
{
}
return macList;
}c#獲取本地IP和MAC地址
實(shí)現(xiàn)代碼
using System;
using System.Management;
using System.Net;
public class Program
{
static void Main(string[] args)
{
try
{
string ip = "";
string mac = "";
ManagementClass mc;
string hostInfo = Dns.GetHostName();
//IP地址
//System.Net.IPAddress[] addressList = Dns.GetHostByName(Dns.GetHostName()).AddressList;這個(gè)過時(shí)
System.Net.IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
for (int i = 0; i < addressList.Length; i++)
{
ip = addressList[i].ToString();
}
//mac地址
mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if (mo["IPEnabled"].ToString() == "True")
{
mac = mo["MacAddress"].ToString();
}
}
//輸出
string outPutStr = "IP:{0},\n MAC地址:{1}";
outPutStr = string.Format(outPutStr, ip, mac);
Console.WriteLine(outPutStr);
}
catch (Exception e)
{ }
Console.ReadLine();
}
}方法補(bǔ)充
1、SendArp 獲取MAC地址
SendARP函數(shù)用來發(fā)送ARP數(shù)據(jù)包并在定義的MAC緩沖區(qū)中返回定義的IP對應(yīng)的MAC地址
SendARP(
IPAddr DestIP,
IPAddr SrcIP,
PULONG pMacAddr,
PULONG PhyAddrLen
);- 第一個(gè)參數(shù)是IP地址的網(wǎng)絡(luò)字節(jié)順序,而不是一個(gè)指針,當(dāng)初我就是賦值成指針而使得獲取不了MAC地址。
- 第二個(gè)參數(shù)填0就可以
- 第三個(gè)參數(shù)是MAC緩沖區(qū)指針
- 第四個(gè)參數(shù)是一個(gè)指向一個(gè)DWORD型數(shù)值為6的指針
代碼如下:
[DllImport("Iphlpapi.dll")]
static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);
/// <summary>
/// SendArp獲取MAC地址
/// </summary>
/// <returns></returns>
public string GetMacAddressBySendARP()
{
StringBuilder strReturn = new StringBuilder();
try
{
System.Net.IPHostEntry Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByName(Dns.GetHostName());
System.Net.IPAddress[] TempAd = Tempaddr.AddressList;
Int32 remote = (int)TempAd[0].Address;
Int64 macinfo = new Int64();
Int32 length = 6;
SendARP(remote, 0, ref macinfo, ref length);
string temp = System.Convert.ToString(macinfo, 16).PadLeft(12, '0').ToUpper();
int x = 12;
for (int i = 0; i < 6; i++)
{
if (i == 5) { strReturn.Append(temp.Substring(x - 2, 2)); }
else { strReturn.Append(temp.Substring(x - 2, 2) + ":"); }
x -= 2;
}
return strReturn.ToString();
}
catch
{
return "";
}
}2、通過適配器信息獲取MAC地址
iphlpapi.dll是Windows IP輔助API應(yīng)用程序接口模塊。其中一個(gè)函數(shù)GetAdaptersAddresses:返回和適配器關(guān)聯(lián)的地址
uint GetAdaptersAddresses(uint Family, uint flags, IntPtr Reserved,IntPtr PAdaptersAddresses, ref uint pOutBufLen);
Family:[輸入]獲得地址族,必須是以下值之一:
- AF_INET (僅返回IPv4地址),
- AF_INET6(僅返回IPv6地址),
- F_UNSPEC(從所有的地址族返回地址)
Flags:[輸入]返回地址類型,這個(gè)參數(shù)為0或是以下值的聯(lián)合值:
- GAA_FLAG_INCLUDE_PREFIX (返回IPv6地址前綴)
- GAA_FLAG_SKIP_UNICAST(不返回unicast地址)
- GAA_FLAG_SKIP_ANYCAST(不返回anycast地址)
- GAA_FLAG_SKIP_FRIENDLY_NAME(不返回適配器的友好名稱)
- GAA_FLAG_SKIP_MULTICAST (不返回多點(diǎn)傳送(multicast)地址)
- GAA_FLAG_SKIP_DNS_SERVER (不返回DNS服務(wù)器地址)
Reserved:調(diào)用程序必須將此參數(shù)置為NULL
pAdapterAddresses:[輸入,輸出] 指向一段IP_ADAPTER_ADDRESSES緩存,成功的話,該緩存包含地址信息。
pOutBufLen:[輸出] 返回pAdapterAddresses所在緩存的大小
返回值:成功,返回0;失敗,返回錯(cuò)誤代碼。
代碼如下
[DllImport("Iphlpapi.dll")]
public static extern uint GetAdaptersAddresses(uint Family, uint flags, IntPtr Reserved,
IntPtr PAdaptersAddresses, ref uint pOutBufLen);
/// <summary>
/// 通過適配器信息獲取MAC地址
/// </summary>
/// <returns></returns>
public string GetMacAddressByAdapter()
{
string macAddress = "";
try
{
IntPtr PAdaptersAddresses = new IntPtr();
uint pOutLen = 100;
PAdaptersAddresses = Marshal.AllocHGlobal(100);
uint ret =
GetAdaptersAddresses(0, 0, (IntPtr)0, PAdaptersAddresses, ref pOutLen);
if (ret == 111)
{
Marshal.FreeHGlobal(PAdaptersAddresses);
PAdaptersAddresses = Marshal.AllocHGlobal((int)pOutLen);
ret = GetAdaptersAddresses(0, 0, (IntPtr)0, PAdaptersAddresses, ref pOutLen);
}
IP_Adapter_Addresses adds = new IP_Adapter_Addresses();
IntPtr pTemp = PAdaptersAddresses;
while (pTemp != (IntPtr)0)
{
Marshal.PtrToStructure(pTemp, adds);
string adapterName = Marshal.PtrToStringAnsi(adds.AdapterName);
string FriendlyName = Marshal.PtrToStringAuto(adds.FriendlyName);
string tmpString = string.Empty;
for (int i = 0; i < 6; i++)
{
tmpString += string.Format("{0:X2}", adds.PhysicalAddress[i]);
if (i < 5)
{
tmpString += ":";
}
}
RegistryKey theLocalMachine = Registry.LocalMachine;
RegistryKey theSystem
= theLocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces");
RegistryKey theInterfaceKey = theSystem.OpenSubKey(adapterName);
if (theInterfaceKey != null)
{
macAddress = tmpString;
break;
}
pTemp = adds.Next;
}
}
catch
{ }
return macAddress;
}3、 通過NetBios獲取MAC地址
NetBIOS(網(wǎng)絡(luò)基本輸入/輸出系統(tǒng))是一套用于網(wǎng)絡(luò)通訊的調(diào)用接口,包含NetBIOS Name和MAC地址等信息。該方法獲取MAC地址的效率較高。
代碼如下:
/// <summary>
/// 通過NetBios獲取MAC地址
/// </summary>
/// <returns></returns>
public string GetMacAddressByNetBios()
{
string macAddress = "";
try
{
string addr = "";
int cb;
ASTAT adapter;
NCB Ncb = new NCB();
char uRetCode;
LANA_ENUM lenum;
Ncb.ncb_command = (byte)NCBCONST.NCBENUM;
cb = Marshal.SizeOf(typeof(LANA_ENUM));
Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
Ncb.ncb_length = (ushort)cb;
uRetCode = Win32API.Netbios(ref Ncb);
lenum = (LANA_ENUM)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(LANA_ENUM));
Marshal.FreeHGlobal(Ncb.ncb_buffer);
if (uRetCode != (short)NCBCONST.NRC_GOODRET)
return "";
for (int i = 0; i < lenum.length; i++)
{
Ncb.ncb_command = (byte)NCBCONST.NCBRESET;
Ncb.ncb_lana_num = lenum.lana[i];
uRetCode = Win32API.Netbios(ref Ncb);
if (uRetCode != (short)NCBCONST.NRC_GOODRET)
return "";
Ncb.ncb_command = (byte)NCBCONST.NCBASTAT;
Ncb.ncb_lana_num = lenum.lana[i];
Ncb.ncb_callname[0] = (byte)'*';
cb = Marshal.SizeOf(typeof(ADAPTER_STATUS)) + Marshal.SizeOf(typeof(NAME_BUFFER)) * (int)NCBCONST.NUM_NAMEBUF;
Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
Ncb.ncb_length = (ushort)cb;
uRetCode = Win32API.Netbios(ref Ncb);
adapter.adapt = (ADAPTER_STATUS)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(ADAPTER_STATUS));
Marshal.FreeHGlobal(Ncb.ncb_buffer);
if (uRetCode == (short)NCBCONST.NRC_GOODRET)
{
if (i > 0)
addr += ":";
addr = string.Format("{0,2:X}:{1,2:X}:{2,2:X}:{3,2:X}:{4,2:X}:{5,2:X}",
adapter.adapt.adapter_address[0],
adapter.adapt.adapter_address[1],
adapter.adapt.adapter_address[2],
adapter.adapt.adapter_address[3],
adapter.adapt.adapter_address[4],
adapter.adapt.adapter_address[5]);
}
}
macAddress = addr.Replace(' ', '0');
}
catch
{
}
return macAddress;
}4、 通過DOS命令獲得MAC地址
這個(gè)就是使用ipconfig命令,并需要在程序中啟用cmd,程序中使用cmd如下即可,
代碼如下:
/// <summary>
/// 通過DOS命令獲得MAC地址
/// </summary>
/// <returns></returns>
public string GetMacAddressByDos()
{
string macAddress = "";
Process p = null;
StreamReader reader = null;
try
{
ProcessStartInfo start = new ProcessStartInfo("cmd.exe");
start.FileName = "ipconfig";
start.Arguments = "/all";
start.CreateNoWindow = true;
start.RedirectStandardOutput = true;
start.RedirectStandardInput = true;
start.UseShellExecute = false;
p = Process.Start(start);
reader = p.StandardOutput;
string line = reader.ReadLine();
while (!reader.EndOfStream)
{
if (line.ToLower().IndexOf("physical address") > 0 || line.ToLower().IndexOf("物理地址") > 0)
{
int index = line.IndexOf(":");
index += 2;
macAddress = line.Substring(index);
macAddress = macAddress.Replace('-', ':');
break;
}
line = reader.ReadLine();
}
}
catch
{
}
finally
{
if (p != null)
{
p.WaitForExit();
p.Close();
}
if (reader != null)
{
reader.Close();
}
}
return macAddress;
}5、 NetworkInterface獲取MAC地址
NetworkInterface,提供網(wǎng)絡(luò)接口的配置和統(tǒng)計(jì)信息。NetworkInterface.GetAllNetworkInterfaces,返回描述本地計(jì)算機(jī)上的網(wǎng)絡(luò)接口的對象。
代碼如下:
/// <summary>
/// 通過網(wǎng)絡(luò)適配器獲取MAC地址
/// </summary>
/// <returns></returns>
public string GetMacAddressByNetworkInformation()
{
string macAddress = "";
try
{
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in nics)
{
if (!adapter.GetPhysicalAddress().ToString().Equals(""))
{
macAddress = adapter.GetPhysicalAddress().ToString();
for (int i = 1; i < 6; i++)
{
macAddress = macAddress.Insert(3 * i - 1, ":");
}
break;
}
}
}
catch
{
}
return macAddress;
}到此這篇關(guān)于C#實(shí)現(xiàn)自動(dòng)獲取電腦MAC地址的文章就介紹到這了,更多相關(guān)C#獲取MAC地址內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
深入多線程之:內(nèi)存柵欄與volatile關(guān)鍵字的使用分析
本篇文章對內(nèi)存柵欄與volatile關(guān)鍵字的使用進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
C#實(shí)現(xiàn)路由器斷開連接,更改公網(wǎng)ip的實(shí)例代碼
C#實(shí)現(xiàn)路由器斷開連接,更改公網(wǎng)ip的實(shí)例代碼,需要的朋友可以參考一下2013-05-05
C#中sqlDataRead 的三種方式遍歷讀取各個(gè)字段數(shù)值的方法
這篇文章主要介紹了C#中 sqlDataRead 的三種方式遍歷讀取各個(gè)字段數(shù)值的方法,每種方法給大家介紹的都非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-09-09
C#實(shí)現(xiàn)將Word轉(zhuǎn)化分享為電子期刊
曾經(jīng)由一個(gè)項(xiàng)目,要求實(shí)現(xiàn)制作電子期刊定期發(fā)送給企業(yè)進(jìn)行閱讀,由編輯人員使用 Microsoft Word先生成PDF文件,然后將生成的PDF文件轉(zhuǎn)化為JPEG文件,最后將JPEG文件生成電子書模式,本文給大家介紹了C#實(shí)現(xiàn)將Word轉(zhuǎn)化分享為電子期刊,需要的朋友可以參考下2023-12-12
C#線程啟動(dòng)的幾種實(shí)現(xiàn)方法小結(jié)
在C#中創(chuàng)建新線程執(zhí)行代碼的幾種方法,包括Thread、Task、ThreadPool等,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-07-07

