C#获取mac

 验证计算机MAC地址进行软件授权是一种通用的方法,C#可以轻松获取计算机的MAC地址,本文采用实际的源代码讲述了两种获取网卡的方式,第一种 方法使用ManagementClass类,只能获取本机的计算机网卡物理地址,第二种方法使用Iphlpapi.dll的SendARP方法,可以获取 本机和其它计算机的MAC地址。

    方法1:使用ManagementClass类

          示例:

        /// <summary>

        /// 获取网卡物理地址

        /// </summary>

        /// <returns></returns>

        public static string getMacAddr_Local()

        {

            string madAddr = null;

            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");

            ManagementObjectCollection moc2 = mc.GetInstances();

            foreach (ManagementObject mo in moc2)

            {

                if (Convert.ToBoolean(mo["IPEnabled"]) == true)

                {

                    madAddr = mo["MacAddress"].ToString();

                    madAddr = madAddr.Replace(':', '-');

                }

                mo.Dispose();

            }

            return madAddr;

        }

 

说明:

   1.需要给项目增加引用:System.Management

    2.在程序开始添加包引入语句:using System.Management;

    3.本方案只能获取本机的MAC地址;

    方法2:使用SendARP类

          示例:

        //下面一种方法可以获取远程的MAC地址

        [DllImport("Iphlpapi.dll")]

        static extern int SendARP(Int32 DestIP, Int32 SrcIP, ref Int64 MacAddr, ref Int32 PhyAddrLen);

        [DllImport("Ws2_32.dll")]

        static extern Int32 inet_addr(string ipaddr);        

        /// <summary>

        /// SendArp获取MAC地址

        /// </summary>

        /// <param name="RemoteIP">目标机器的IP地址如(192.168.1.1)</param>

        /// <returns>目标机器的mac 地址</returns>

        public static string getMacAddr_Remote(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();

            }

        }

 

说明:

    1.在程序开始添加包引入语句:using System.Runtime.InteropServices;

    2.该方法可以获取远程计算机的MAC地址;

 

C#获得本机MAC地址 - [Coding](转)

刚开始在机房推广我们组的系统,用户注册就失效了,debug了许久之后,发现居然是一直都在使用的获得MAC的地址的方法居然失效了——数据库报异常,以MAC为主键的表提示主键重复了   ,怎么可能啊?就好像GUID重复一样!!!!

对原来获得MAC的地址的代码做了测试,才发现在我机子居然运行的结果和在cmd下ipconfig的结果不同 ,仅是一个vm的mac。源码如下:

string MacAddress;

//设置MAC地址

string MAC=""; 

ManagementClass MC = new ManagementClass ( "Win32_NetworkAdapterConfiguration" ); 

ManagementObjectCollection MOC = MC.GetInstances(); 

foreach ( ManagementObject moc in MOC ) 

{ 

 if ( moc["IPEnabled"].ToString() == "True") 

 { 

  MAC = moc["MacAddress"].ToString(); 

 }

}

MacAddress=MAC;

经过在网络上寻找,找到了获得本机mac的方法,只是结果是一个ArrayList,运行的结果和cmd下命令一样,只是包括了一个真的mac和两个vm的mac,源码如下:

using System.Management;

using System.Runtime.InteropServices; 

using System.Text;  

using System.Text.RegularExpressions;



string strsearch=string.Format(@"SELECT MACAddress FROM Win32_NetworkAdapter WHERE ((MACAddress Is Not NULL)AND (Manufacturer <> 'Microsoft'))");



System.Management.ManagementObjectSearcher msearch=new ManagementObjectSearcher();  

msearch.Scope=new ManagementScope(@"root/CIMV2"); 

msearch.Query=new ObjectQuery(strsearch); 

ArrayList MacList  =new ArrayList();

int i =0;

try 

{ 

 if((msearch.Get().Count<1) || (msearch.Get()==null)) 

 { 

  MessageBox.Show("No MAC Address!"); 

 } 

 else 

 { 

  MessageBox.Show("MAC Address No. is : "+ msearch.Get().Count.ToString()); 

  foreach(System.Management.ManagementObject mymac in msearch.Get()) 

  { 

   string str1=string.Format("MAC{0} address:{1}",i.ToString(),mymac["MACAddress"].ToString()); 

   MessageBox.Show("MAC Address "+i.ToString()+":"+str1); 

   MacList.Add(str1);

   i++; 

  } 

 } 

} 

catch(Exception ex) 

{ 

 string msg=ex.Message.ToString(); 

 MessageBox.Show("erro", msg); 

}

由于没有办法确定获得mac那个真实的,所以又用了第三个方法,通过IP地址获得mac:

using System.Management;

using System.Runtime.InteropServices; 

using System.Text;  

using System.Text.RegularExpressions; 



[DllImport("Iphlpapi.dll")]   

private static extern int SendARP(Int32 dest,Int32 host,ref Int32 mac,ref Int32 length);   

[DllImport("Ws2_32.dll")]   

private static extern Int32 inet_addr(string ip);  



string IPAddress=System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0].ToString();

MessageBox.Show("ip: "+IPAddress);

string mac = this.GetMACFromIP(IPAddress);

MessageBox.Show("mac: "+mac);



private   string   GetMACFromIP(string   A_strIP)   

  {   

   string   strRet   =   "Unknown";   

    

   string   strIPPattern   =   @"^/d+/./d+/./d+/./d+$";   

    

   Regex   objRex   =new   Regex(strIPPattern);   

    

   if(objRex.IsMatch(A_strIP)   ==   true)   

   {   

    Int32   intDest   =   inet_addr(A_strIP);   

    Int32   []   arrMAC   =   new   Int32[2];   

    Int32   intLen   =   6;   

    

    int   intResult   =   SendARP(intDest,0,ref   arrMAC[0],ref   intLen);   

    

    if(intResult   ==   0)   

    {   

     Byte   []   arrbyte   =   new   Byte[8];   

     arrbyte[5]   =   (Byte)(arrMAC[1]   >>   8);   

     arrbyte[4]   =   (Byte)arrMAC[1];   

     arrbyte[3]   =   (Byte)(arrMAC[0]   >>   24);   

     arrbyte[2]   =   (Byte)(arrMAC[0]   >>   16);   

     arrbyte[1]   =   (Byte)(arrMAC[0]   >>   8);   

     arrbyte[0]   =   (Byte)arrMAC[0];   

    

     StringBuilder   strbMAC   =   new   StringBuilder();   

    

     for(int   intIndex   =   0   ;intIndex   <   6;intIndex   ++)   

     {   

      if(intIndex   >   0)   strbMAC.Append("-");   

      strbMAC.Append(arrbyte[intIndex].ToString("X2"));   

     }   

     strRet   =   strbMAC.ToString();   

    }   

   }   

   return   strRet;   

  }

 

你可能感兴趣的:(mac)