C#获取MAC地址的几种方法(补充版)

来自:http://blog.csdn.net/yysyangyangyangshan/article/details/7091783

关于获取本地电脑的MAC地址,除了前面说过的根据WMI获取http://blog.csdn.net/yysyangyangyangshan/article/details/6803787,其实还有好几种方式来获取mac地址,下面一一道来。

首先需要用到的一些方法和类:

  1. public enum NCBCONST
  2. {
  3. NCBNAMSZ = 16,
  4. MAX_LANA = 254,
  5. NCBENUM = 0x37,
  6. NRC_GOODRET = 0x00,
  7. NCBRESET = 0x32,
  8. NCBASTAT = 0x33,
  9. NUM_NAMEBUF = 30,
  10. }
  11. [StructLayout(LayoutKind.Sequential)]
  12. public struct ADAPTER_STATUS
  13. {
  14. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
  15. public byte[] adapter_address;
  16. public byte rev_major;
  17. public byte reserved0;
  18. public byte adapter_type;
  19. public byte rev_minor;
  20. public ushort duration;
  21. public ushort frmr_recv;
  22. public ushort frmr_xmit;
  23. public ushort iframe_recv_err;
  24. public ushort xmit_aborts;
  25. public uint xmit_success;
  26. public uint recv_success;
  27. public ushort iframe_xmit_err;
  28. public ushort recv_buff_unavail;
  29. public ushort t1_timeouts;
  30. public ushort ti_timeouts;
  31. public uint reserved1;
  32. public ushort free_ncbs;
  33. public ushort max_cfg_ncbs;
  34. public ushort max_ncbs;
  35. public ushort xmit_buf_unavail;
  36. public ushort max_dgram_size;
  37. public ushort pending_sess;
  38. public ushort max_cfg_sess;
  39. public ushort max_sess;
  40. public ushort max_sess_pkt_size;
  41. public ushort name_count;
  42. }
  43. [StructLayout(LayoutKind.Sequential)]
  44. public struct NAME_BUFFER
  45. {
  46. [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
  47. public byte[] name;
  48. public byte name_num;
  49. public byte name_flags;
  50. }
  51. [StructLayout(LayoutKind.Sequential)]
  52. public struct NCB
  53. {
  54. public byte ncb_command;
  55. public byte ncb_retcode;
  56. public byte ncb_lsn;
  57. public byte ncb_num;
  58. public IntPtr ncb_buffer;
  59. public ushort ncb_length;
  60. [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
  61. public byte[] ncb_callname;
  62. [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
  63. public byte[] ncb_name;
  64. public byte ncb_rto;
  65. public byte ncb_sto;
  66. public IntPtr ncb_post;
  67. public byte ncb_lana_num;
  68. public byte ncb_cmd_cplt;
  69. [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
  70. public byte[] ncb_reserve;
  71. public IntPtr ncb_event;
  72. }
  73. [StructLayout(LayoutKind.Sequential)]
  74. public struct LANA_ENUM
  75. {
  76. public byte length;
  77. [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.MAX_LANA)]
  78. public byte[] lana;
  79. }
  80. [StructLayout(LayoutKind.Auto)]
  81. public struct ASTAT
  82. {
  83. public ADAPTER_STATUS adapt;
  84. [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NUM_NAMEBUF)]
  85. public NAME_BUFFER[] NameBuff;
  86. }
  87. public class Win32API
  88. {
  89. [DllImport("NETAPI32.DLL")]
  90. public static extern char Netbios(ref NCB ncb);
  91. }
  92. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  93. public class IP_Adapter_Addresses
  94. {
  95. public uint Length;
  96. public uint IfIndex;
  97. public IntPtr Next;
  98. public IntPtr AdapterName;
  99. public IntPtr FirstUnicastAddress;
  100. public IntPtr FirstAnycastAddress;
  101. public IntPtr FirstMulticastAddress;
  102. public IntPtr FirstDnsServerAddress;
  103. public IntPtr DnsSuffix;
  104. public IntPtr Description;
  105. public IntPtr FriendlyName;
  106. [MarshalAs(UnmanagedType.ByValArray,
  107. SizeConst = 8)]
  108. public Byte[] PhysicalAddress;
  109. public uint PhysicalAddressLength;
  110. public uint flags;
  111. public uint Mtu;
  112. public uint IfType;
  113. public uint OperStatus;
  114. public uint Ipv6IfIndex;
  115. public uint ZoneIndices;
  116. public IntPtr FirstPrefix;
  117. }
    public enum NCBCONST
    {
        NCBNAMSZ = 16,             
        MAX_LANA = 254,            
        NCBENUM = 0x37,            
        NRC_GOODRET = 0x00,        
        NCBRESET = 0x32,           
        NCBASTAT = 0x33,           
        NUM_NAMEBUF = 30,          
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct ADAPTER_STATUS
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 6)]
        public byte[] adapter_address;
        public byte rev_major;
        public byte reserved0;
        public byte adapter_type;
        public byte rev_minor;
        public ushort duration;
        public ushort frmr_recv;
        public ushort frmr_xmit;
        public ushort iframe_recv_err;
        public ushort xmit_aborts;
        public uint xmit_success;
        public uint recv_success;
        public ushort iframe_xmit_err;
        public ushort recv_buff_unavail;
        public ushort t1_timeouts;
        public ushort ti_timeouts;
        public uint reserved1;
        public ushort free_ncbs;
        public ushort max_cfg_ncbs;
        public ushort max_ncbs;
        public ushort xmit_buf_unavail;
        public ushort max_dgram_size;
        public ushort pending_sess;
        public ushort max_cfg_sess;
        public ushort max_sess;
        public ushort max_sess_pkt_size;
        public ushort name_count;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct NAME_BUFFER
    {
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
        public byte[] name;
        public byte name_num;
        public byte name_flags;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct NCB
    {
        public byte ncb_command;
        public byte ncb_retcode;
        public byte ncb_lsn;
        public byte ncb_num;
        public IntPtr ncb_buffer;
        public ushort ncb_length;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
        public byte[] ncb_callname;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NCBNAMSZ)]
        public byte[] ncb_name;
        public byte ncb_rto;
        public byte ncb_sto;
        public IntPtr ncb_post;
        public byte ncb_lana_num;
        public byte ncb_cmd_cplt;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
        public byte[] ncb_reserve;
        public IntPtr ncb_event;
    }

    [StructLayout(LayoutKind.Sequential)]
    public struct LANA_ENUM
    {
        public byte length;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.MAX_LANA)]
        public byte[] lana;
    }

    [StructLayout(LayoutKind.Auto)]
    public struct ASTAT
    {
        public ADAPTER_STATUS adapt;
        [MarshalAs(UnmanagedType.ByValArray, SizeConst = (int)NCBCONST.NUM_NAMEBUF)]
        public NAME_BUFFER[] NameBuff;
    }
    public class Win32API
    {
        [DllImport("NETAPI32.DLL")]
        public static extern char Netbios(ref   NCB ncb);
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    public class IP_Adapter_Addresses
    {
        public uint Length;
        public uint IfIndex;
        public IntPtr Next;

        public IntPtr AdapterName;
        public IntPtr FirstUnicastAddress;
        public IntPtr FirstAnycastAddress;
        public IntPtr FirstMulticastAddress;
        public IntPtr FirstDnsServerAddress;

        public IntPtr DnsSuffix;
        public IntPtr Description;

        public IntPtr FriendlyName;

        [MarshalAs(UnmanagedType.ByValArray,
             SizeConst = 8)]
        public Byte[] PhysicalAddress;

        public uint PhysicalAddressLength;
        public uint flags;
        public uint Mtu;
        public uint IfType;

        public uint OperStatus;

        public uint Ipv6IfIndex;
        public uint ZoneIndices;

        public IntPtr FirstPrefix;
    }

1、 SendArp 获取MAC地址

SendARP函数用来发送ARP数据包并在定义的MAC缓冲区中返回定义的IP对应的MAC地址

SendARP(

IPAddr DestIP,

IPAddr SrcIP,

PULONG pMacAddr,

PULONG PhyAddrLen

);

第一个参数是IP地址的网络字节顺序,而不是一个指针,当初我就是赋值成指针而使得获取不了MAC地址。

第二个参数填0就可以

第三个参数是MAC缓冲区指针

第四个参数是一个指向一个DWORD型数值为6的指针

代码如下:

  1. [DllImport("Iphlpapi.dll")]
  2. static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);
  3. /// <summary>
  4. /// SendArp获取MAC地址
  5. /// </summary>
  6. /// <returns></returns>
  7. public string GetMacAddressBySendARP()
  8. {
  9. StringBuilder strReturn = new StringBuilder();
  10. try
  11. {
  12. System.Net.IPHostEntry Tempaddr = (System.Net.IPHostEntry)Dns.GetHostByName(Dns.GetHostName());
  13. System.Net.IPAddress[] TempAd = Tempaddr.AddressList;
  14. Int32 remote = (int)TempAd[0].Address;
  15. Int64 macinfo = new Int64();
  16. Int32 length = 6;
  17. SendARP(remote, 0, ref macinfo, ref length);
  18. string temp = System.Convert.ToString(macinfo, 16).PadLeft(12, '0').ToUpper();
  19. int x = 12;
  20. for (int i = 0; i < 6; i++)
  21. {
  22. if (i == 5) { strReturn.Append(temp.Substring(x - 2, 2)); }
  23. else { strReturn.Append(temp.Substring(x - 2, 2) + ":"); }
  24. x -= 2;
  25. }
  26. return strReturn.ToString();
  27. }
  28. catch
  29. {
  30. return "";
  31. }
  32. }
        [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应用程序接口模块。其中一个函数GetAdaptersAddresses:返回和适配器关联的地址

uint GetAdaptersAddresses(uint Family, uint flags, IntPtr Reserved,

IntPtr PAdaptersAddresses, ref uint pOutBufLen);

Family:[输入]获得地址族,必须是以下值之一:

AF_INET (仅返回IPv4地址),

AF_INET6(仅返回IPv6地址),

AF_UNSPEC(从所有的地址族返回地址)

Flags:[输入]返回地址类型,这个参数为0或是以下值的联合值:

GAA_FLAG_INCLUDE_PREFIX (返回IPv6地址前缀)

GAA_FLAG_SKIP_UNICAST(不返回unicast地址)

GAA_FLAG_SKIP_ANYCAST(不返回anycast地址)

GAA_FLAG_SKIP_FRIENDLY_NAME(不返回适配器的友好名称)

GAA_FLAG_SKIP_MULTICAST (不返回多点传送(multicast)地址)

GAA_FLAG_SKIP_DNS_SERVER (不返回DNS服务器地址)

Reserved:调用程序必须将此参数置为NULL

pAdapterAddresses:[输入,输出] 指向一段IP_ADAPTER_ADDRESSES缓存,成功的话,该缓存包含地址信息。

pOutBufLen:[输出] 返回pAdapterAddresses所在缓存的大小

返回值:成功,返回0;失败,返回错误代码。

代码如下:

  1. [DllImport("Iphlpapi.dll")]
  2. public static extern uint GetAdaptersAddresses(uint Family, uint flags, IntPtr Reserved,
  3. IntPtr PAdaptersAddresses, ref uint pOutBufLen);
  4. /// <summary>
  5. /// 通过适配器信息获取MAC地址
  6. /// </summary>
  7. /// <returns></returns>
  8. public string GetMacAddressByAdapter()
  9. {
  10. string macAddress = "";
  11. try
  12. {
  13. IntPtr PAdaptersAddresses = new IntPtr();
  14. uint pOutLen = 100;
  15. PAdaptersAddresses = Marshal.AllocHGlobal(100);
  16. uint ret =
  17. GetAdaptersAddresses(0, 0, (IntPtr)0, PAdaptersAddresses, ref pOutLen);
  18. if (ret == 111)
  19. {
  20. Marshal.FreeHGlobal(PAdaptersAddresses);
  21. PAdaptersAddresses = Marshal.AllocHGlobal((int)pOutLen);
  22. ret = GetAdaptersAddresses(0, 0, (IntPtr)0, PAdaptersAddresses, ref pOutLen);
  23. }
  24. IP_Adapter_Addresses adds = new IP_Adapter_Addresses();
  25. IntPtr pTemp = PAdaptersAddresses;
  26. while (pTemp != (IntPtr)0)
  27. {
  28. Marshal.PtrToStructure(pTemp, adds);
  29. string adapterName = Marshal.PtrToStringAnsi(adds.AdapterName);
  30. string FriendlyName = Marshal.PtrToStringAuto(adds.FriendlyName);
  31. string tmpString = string.Empty;
  32. for (int i = 0; i < 6; i++)
  33. {
  34. tmpString += string.Format("{0:X2}", adds.PhysicalAddress[i]);
  35. if (i < 5)
  36. {
  37. tmpString += ":";
  38. }
  39. }
  40. RegistryKey theLocalMachine = Registry.LocalMachine;
  41. RegistryKey theSystem
  42. = theLocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces");
  43. RegistryKey theInterfaceKey = theSystem.OpenSubKey(adapterName);
  44. if (theInterfaceKey != null)
  45. {
  46. macAddress = tmpString;
  47. break;
  48. }
  49. pTemp = adds.Next;
  50. }
  51. }
  52. catch
  53. { }
  54. return macAddress;
  55. }
        [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(网络基本输入/输出系统)是一套用于网络通讯的调用接口,包含NetBIOS Name和MAC地址等信息。该方法获取MAC地址的效率较高。

代码如下:

  1. /// <summary>
  2. /// 通过NetBios获取MAC地址
  3. /// </summary>
  4. /// <returns></returns>
  5. public string GetMacAddressByNetBios()
  6. {
  7. string macAddress = "";
  8. try
  9. {
  10. string addr = "";
  11. int cb;
  12. ASTAT adapter;
  13. NCB Ncb = new NCB();
  14. char uRetCode;
  15. LANA_ENUM lenum;
  16. Ncb.ncb_command = (byte)NCBCONST.NCBENUM;
  17. cb = Marshal.SizeOf(typeof(LANA_ENUM));
  18. Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
  19. Ncb.ncb_length = (ushort)cb;
  20. uRetCode = Win32API.Netbios(ref Ncb);
  21. lenum = (LANA_ENUM)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(LANA_ENUM));
  22. Marshal.FreeHGlobal(Ncb.ncb_buffer);
  23. if (uRetCode != (short)NCBCONST.NRC_GOODRET)
  24. return "";
  25. for (int i = 0; i < lenum.length; i++)
  26. {
  27. Ncb.ncb_command = (byte)NCBCONST.NCBRESET;
  28. Ncb.ncb_lana_num = lenum.lana[i];
  29. uRetCode = Win32API.Netbios(ref Ncb);
  30. if (uRetCode != (short)NCBCONST.NRC_GOODRET)
  31. return "";
  32. Ncb.ncb_command = (byte)NCBCONST.NCBASTAT;
  33. Ncb.ncb_lana_num = lenum.lana[i];
  34. Ncb.ncb_callname[0] = (byte)'*';
  35. cb = Marshal.SizeOf(typeof(ADAPTER_STATUS)) + Marshal.SizeOf(typeof(NAME_BUFFER)) * (int)NCBCONST.NUM_NAMEBUF;
  36. Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
  37. Ncb.ncb_length = (ushort)cb;
  38. uRetCode = Win32API.Netbios(ref Ncb);
  39. adapter.adapt = (ADAPTER_STATUS)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(ADAPTER_STATUS));
  40. Marshal.FreeHGlobal(Ncb.ncb_buffer);
  41. if (uRetCode == (short)NCBCONST.NRC_GOODRET)
  42. {
  43. if (i > 0)
  44. addr += ":";
  45. addr = string.Format("{0,2:X}:{1,2:X}:{2,2:X}:{3,2:X}:{4,2:X}:{5,2:X}",
  46. adapter.adapt.adapter_address[0],
  47. adapter.adapt.adapter_address[1],
  48. adapter.adapt.adapter_address[2],
  49. adapter.adapt.adapter_address[3],
  50. adapter.adapt.adapter_address[4],
  51. adapter.adapt.adapter_address[5]);
  52. }
  53. }
  54. macAddress = addr.Replace(' ', '0');
  55. }
  56. catch
  57. {
  58. }
  59. return macAddress;
  60. }
        /// <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地址

这个就是使用ipconfig命令,并需要在程序中启用cmd,程序中使用cmd如下即可,或参见http://blog.csdn.net/yysyangyangyangshan/article/details/6799489,

代码如下:

  1. /// <summary>
  2. /// 通过DOS命令获得MAC地址
  3. /// </summary>
  4. /// <returns></returns>
  5. public string GetMacAddressByDos()
  6. {
  7. string macAddress = "";
  8. Process p = null;
  9. StreamReader reader = null;
  10. try
  11. {
  12. ProcessStartInfo start = new ProcessStartInfo("cmd.exe");
  13. start.FileName = "ipconfig";
  14. start.Arguments = "/all";
  15. start.CreateNoWindow = true;
  16. start.RedirectStandardOutput = true;
  17. start.RedirectStandardInput = true;
  18. start.UseShellExecute = false;
  19. p = Process.Start(start);
  20. reader = p.StandardOutput;
  21. string line = reader.ReadLine();
  22. while (!reader.EndOfStream)
  23. {
  24. if (line.ToLower().IndexOf("physical address") > 0 || line.ToLower().IndexOf("物理地址") > 0)
  25. {
  26. int index = line.IndexOf(":");
  27. index += 2;
  28. macAddress = line.Substring(index);
  29. macAddress = macAddress.Replace('-', ':');
  30. break;
  31. }
  32. line = reader.ReadLine();
  33. }
  34. }
  35. catch
  36. {
  37. }
  38. finally
  39. {
  40. if (p != null)
  41. {
  42. p.WaitForExit();
  43. p.Close();
  44. }
  45. if (reader != null)
  46. {
  47. reader.Close();
  48. }
  49. }
  50. return macAddress;
  51. }
        /// <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,提供网络接口的配置和统计信息。NetworkInterface.GetAllNetworkInterfaces,返回描述本地计算机上的网络接口的对象。

代码如下:

  1. /// <summary>
  2. /// 通过网络适配器获取MAC地址
  3. /// </summary>
  4. /// <returns></returns>
  5. public string GetMacAddressByNetworkInformation()
  6. {
  7. string macAddress = "";
  8. try
  9. {
  10. NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
  11. foreach (NetworkInterface adapter in nics)
  12. {
  13. if (!adapter.GetPhysicalAddress().ToString().Equals(""))
  14. {
  15. macAddress = adapter.GetPhysicalAddress().ToString();
  16. for (int i = 1; i < 6; i++)
  17. {
  18. macAddress = macAddress.Insert(3 * i - 1, ":");
  19. }
  20. break;
  21. }
  22. }
  23. }
  24. catch
  25. {
  26. }
  27. return macAddress;
  28. }
        /// <summary>
        /// 通过网络适配器获取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;
        }

完整代码下载地址:http://download.csdn.net/download/yysyangyangyangshan/3949946


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值