最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#實(shí)現(xiàn)自動(dòng)獲取電腦MAC地址

 更新時(shí)間:2025年09月16日 15:08:57   作者:加號(hào)3  
這篇文章主要為大家介紹了多種獲取本地電腦MAC地址的方法,包括使用WMI、SendARP、適配器信息等,每種方法都提供了詳細(xì)步驟和代碼示例,希望對大家有所幫助

自動(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)文章

  • C#生成隨機(jī)數(shù)功能示例

    C#生成隨機(jī)數(shù)功能示例

    這篇文章主要介紹了C#生成隨機(jī)數(shù)功能,涉及C#數(shù)學(xué)運(yùn)算與字符串操作相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2017-01-01
  • C#通過反射打開相應(yīng)窗體方法分享

    C#通過反射打開相應(yīng)窗體方法分享

    本文章來給各位同學(xué)介紹關(guān)于C#單擊菜單欄或工具欄時(shí)通過反射打開窗體的方法,有需要了解的朋友可進(jìn)入?yún)⒖紖⒖肌?/div> 2015-05-05
  • C# 使用Fiddler捕獲本地HttpClient發(fā)出的請求操作

    C# 使用Fiddler捕獲本地HttpClient發(fā)出的請求操作

    這篇文章主要介紹了C# 使用Fiddler捕獲本地HttpClient發(fā)出的請求操作,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-10-10
  • C#代碼實(shí)現(xiàn)在PowerPoint中創(chuàng)建組合圖表

    C#代碼實(shí)現(xiàn)在PowerPoint中創(chuàng)建組合圖表

    在 PowerPoint 中,組合圖表是一種將兩種或多種不同圖表類型合并到同一圖表中的圖表形式,本文我們就來看看如何使用C#代碼實(shí)現(xiàn)在PowerPoint中創(chuàng)建組合圖表吧
    2026-04-04
  • C#實(shí)現(xiàn)拆分合并Word表格中的單元格

    C#實(shí)現(xiàn)拆分合并Word表格中的單元格

    我們在使用Word制作表格時(shí),由于表格較為復(fù)雜,只是簡單的插入行、列并不能滿足我們的需要。要做一個(gè)完整的表格,很多時(shí)候需要將單元格進(jìn)行拆分或者合并。本文將詳細(xì)為您介紹在Word表格中拆分或合并單元格的思路及方法,希望對大家有所幫助
    2022-12-12
  • C# 開發(fā)日志本地化工具

    C# 開發(fā)日志本地化工具

    這篇文章主要介紹了C# 開發(fā)日志本地化工具的步驟,幫助大家更好的理解和學(xué)習(xí)使用c#,感興趣的朋友可以了解下
    2021-02-02
  • c#標(biāo)準(zhǔn)idispose模式使用示例

    c#標(biāo)準(zhǔn)idispose模式使用示例

    下面將把C#里實(shí)現(xiàn)IDispose模式的代碼展現(xiàn)出來,大家一起來學(xué)習(xí)一下,它的使用場合也很多的,當(dāng)我們手動(dòng)對網(wǎng)站,數(shù)據(jù)庫作封裝時(shí),都會(huì)用的到
    2014-02-02
  • C# Onnx CenterNet實(shí)現(xiàn)目標(biāo)檢測的示例詳解

    C# Onnx CenterNet實(shí)現(xiàn)目標(biāo)檢測的示例詳解

    這篇文章主要為大家詳細(xì)介紹了C# Onnx CenterNet實(shí)現(xiàn)目標(biāo)檢測的相關(guān)知識(shí),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-12-12
  • C#中Func委托的實(shí)現(xiàn)

    C#中Func委托的實(shí)現(xiàn)

    Func是C#中的泛型委托,用于封裝具有返回值的方法,支持最多16個(gè)輸入?yún)?shù),并始終返回最后一個(gè)泛型參數(shù)指定的類型,下面就來詳細(xì)的介紹一下Func委托的使用,感興趣的可以了解一下
    2025-11-11
  • c#操作sqlserver數(shù)據(jù)庫的簡單示例

    c#操作sqlserver數(shù)據(jù)庫的簡單示例

    這篇文章主要介紹了c#操作sqlserver數(shù)據(jù)庫的簡單示例,需要的朋友可以參考下
    2014-04-04

最新評(píng)論

遵化市| 龙川县| 赤峰市| 奉节县| 昌平区| 永平县| 甘谷县| 西平县| 梧州市| 屯昌县| 汝城县| 新郑市| 正蓝旗| 玛曲县| 哈密市| 桃园县| 北京市| 哈巴河县| 长岭县| 丘北县| 慈溪市| 郴州市| 东乌珠穆沁旗| 通化市| 济南市| 陆良县| 宁强县| 乌兰察布市| 堆龙德庆县| 德兴市| 江门市| 交口县| 东城区| 专栏| 松桃| 英吉沙县| 浑源县| 修水县| 台州市| 白城市| 页游|