Mac地址自动生成器核心处理类

1.更新MAC地址
  将注册表中的键值添加上MAC地址
2.重新连接网络
  试过了3个方法:
     ManagementClass最新提供了Disable,Enable方法,但只支持Vista操作系统
    Shell.dll的方法,可以实现,但处理起来很烦,另外在重新连接时显示“启动中”提示框,不友好。
  NetSharingManagerClass 的Disconnect, Connect方法,可以实现,但有一个问题是,会重新更新IP地址,有明显感觉等。
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Microsoft.Win32;
  6. using System.Net.NetworkInformation;
  7. using System.Management;
  8. using System.Threading;
  9. using System.Runtime.InteropServices;
  10. using NETCONLib;
  11. namespace DynamicMAC
  12. {
  13.     public class MACHelper
  14.     {
  15.         [DllImport("wininet.dll")]
  16.         private extern static bool InternetGetConnectedState(int Description, int ReservedValue);
  17.         /// 
  18.         /// 是否能连接上Internet
  19.         /// 
  20.         /// 
  21.         public bool IsConnectedToInternet()
  22.         {
  23.             int Desc = 0;
  24.             return InternetGetConnectedState(Desc, 0);
  25.         }
  26.         /// 
  27.         /// 获取MAC地址
  28.         /// 
  29.         public string GetMACAddress()
  30.         {
  31.             //得到 MAC的注册表键
  32.             RegistryKey macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control")
  33.                 .OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}");
  34.             IList<string> list = macRegistry.GetSubKeyNames().ToList();
  35.             IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
  36.             NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
  37.             var adapter = nics.First(o => o.Name == "本地连接");
  38.             if (adapter == null)
  39.                 return null;
  40.             return string.Empty;
  41.         }
  42.         /// 
  43.         /// 设置MAC地址
  44.         /// 
  45.         /// 
  46.         public void SetMACAddress(string newMac)
  47.         {
  48.             string macAddress;
  49.             string index = GetAdapterIndex(out macAddress);
  50.             if (index == null)
  51.                 return;
  52.             //得到 MAC的注册表键
  53.             RegistryKey macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control")
  54.                 .OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}").OpenSubKey(index, true);
  55.             if (string.IsNullOrEmpty(newMac))
  56.             {
  57.                 macRegistry.DeleteValue("NetworkAddress");
  58.             }
  59.             else
  60.             {
  61.                 macRegistry.SetValue("NetworkAddress", newMac);
  62.                 macRegistry.OpenSubKey("Ndi"true).OpenSubKey("params"true).OpenSubKey("NetworkAddress"true).SetValue("Default", newMac);
  63.                 macRegistry.OpenSubKey("Ndi"true).OpenSubKey("params"true).OpenSubKey("NetworkAddress"true).SetValue("ParamDesc""Network Address");
  64.             }
  65.             Thread oThread = new Thread(new ThreadStart(ReConnect));//new Thread to ReConnect
  66.             oThread.Start();
  67.         }
  68.         /// 
  69.         /// 重设MAC地址
  70.         /// 
  71.         public void ResetMACAddress()
  72.         {
  73.             SetMACAddress(string.Empty);
  74.         }
  75.         /// 
  76.         /// 重新连接
  77.         /// 
  78.         private void ReConnect()
  79.         {
  80.             NetSharingManagerClass netSharingMgr = new NetSharingManagerClass();
  81.             INetSharingEveryConnectionCollection connections = netSharingMgr.EnumEveryConnection;
  82.             foreach (INetConnection connection in connections)
  83.             {
  84.                 INetConnectionProps connProps = netSharingMgr.get_NetConnectionProps(connection);
  85.                 if (connProps.MediaType == tagNETCON_MEDIATYPE.NCM_LAN)
  86.                 {
  87.                     connection.Disconnect(); //禁用网络
  88.                     connection.Connect();    //启用网络
  89.                 }
  90.             }
  91.         }
  92.         /// 
  93.         /// 生成随机MAC地址
  94.         /// 
  95.         /// 
  96.         public string CreateNewMacAddress()
  97.         {
  98.             //return "0016D3B5C493";
  99.             int min = 0;
  100.             int max = 16;
  101.             Random ro = new Random();
  102.             var sn = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}",
  103.                ro.Next(min, max).ToString("x"),//0
  104.                ro.Next(min, max).ToString("x"),//
  105.                ro.Next(min, max).ToString("x"),
  106.                ro.Next(min, max).ToString("x"),
  107.                ro.Next(min, max).ToString("x"),
  108.                ro.Next(min, max).ToString("x"),//5
  109.                ro.Next(min, max).ToString("x"),
  110.                ro.Next(min, max).ToString("x"),
  111.                ro.Next(min, max).ToString("x"),
  112.                ro.Next(min, max).ToString("x"),
  113.                ro.Next(min, max).ToString("x"),//10
  114.                ro.Next(min, max).ToString("x")
  115.                 ).ToUpper();
  116.             return sn;
  117.         }
  118.         /// 
  119.         /// 得到Mac地址及注册表对应Index
  120.         /// 
  121.         /// 
  122.         /// 
  123.         public string GetAdapterIndex(out string macAddress)
  124.         {
  125.             ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
  126.             ManagementObjectCollection colMObj = oMClass.GetInstances();
  127.             macAddress = string.Empty;
  128.             int indexString = 1;
  129.             foreach (ManagementObject objMO in colMObj)
  130.             {
  131.                 indexString++;
  132.                 if (objMO["MacAddress"] != null && (bool)objMO["IPEnabled"] == true)
  133.                 {
  134.                     macAddress = objMO["MacAddress"].ToString().Replace(":""");
  135.                     break;
  136.                 }
  137.             }
  138.             if (macAddress == string.Empty)
  139.                 return null;
  140.             else
  141.                 return indexString.ToString().PadLeft(4, '0');
  142.         }
  143.         #region Temp
  144.         public void noting()
  145.         {
  146.             //ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
  147.             ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapter");
  148.             ManagementObjectCollection colMObj = oMClass.GetInstances();
  149.             foreach (ManagementObject objMO in colMObj)
  150.             {
  151.                 if (objMO["MacAddress"] != null)
  152.                 {
  153.                     if (objMO["Name"] != null)
  154.                     {
  155.                         //objMO.InvokeMethod("Reset", null);
  156.                         objMO.InvokeMethod("Disable"null);//Vista only
  157.                         objMO.InvokeMethod("Enable"null);//Vista only
  158.                     }
  159.                     //if ((bool)objMO["IPEnabled"] == true)
  160.                     //{
  161.                     //    //Console.WriteLine(objMO["MacAddress"].ToString());
  162.                     //    //objMO.SetPropertyValue("MacAddress", CreateNewMacAddress());
  163.                     //    //objMO["MacAddress"] = CreateNewMacAddress();
  164.                     //    //objMO.InvokeMethod("Disable", null);
  165.                     //    //objMO.InvokeMethod("Enable", null);
  166.                     //    //objMO.Path.ReleaseDHCPLease();
  167.                     //    var iObj = objMO.GetMethodParameters("EnableDHCP");
  168.                     //    var oObj = objMO.InvokeMethod("ReleaseDHCPLease", null, null);
  169.                     //    Thread.Sleep(100);
  170.                     //    objMO.InvokeMethod("RenewDHCPLease", null, null);
  171.                     //}
  172.                 }
  173.             }
  174.         }
  175.         public void no()
  176.         {
  177.             Shell32.Folder networkConnectionsFolder = GetNetworkConnectionsFolder();
  178.             if (networkConnectionsFolder == null)
  179.             {
  180.                 Console.WriteLine("Network connections folder not found.");
  181.                 return;
  182.             }
  183.             Shell32.FolderItem2 networkConnection = GetNetworkConnection(networkConnectionsFolder, string.Empty);
  184.             if (networkConnection == null)
  185.             {
  186.                 Console.WriteLine("Network connection not found.");
  187.                 return;
  188.             }
  189.             Shell32.FolderItemVerb verb;
  190.             try
  191.             {
  192.                 IsNetworkConnectionEnabled(networkConnection, out verb);
  193.                 verb.DoIt();
  194.                 Thread.Sleep(1000);
  195.                 IsNetworkConnectionEnabled(networkConnection, out verb);
  196.                 verb.DoIt();
  197.             }
  198.             catch (ArgumentException ex)
  199.             {
  200.                 Console.WriteLine(ex.Message);
  201.             }
  202.         }
  203.         /// 
  204.         /// Gets the Network Connections folder in the control panel.
  205.         /// 
  206.         /// The Folder for the Network Connections folder, or null if it was not found.
  207.         static Shell32.Folder GetNetworkConnectionsFolder()
  208.         {
  209.             Shell32.Shell sh = new Shell32.Shell();
  210.             Shell32.Folder controlPanel = sh.NameSpace(3); // Control panel
  211.             Shell32.FolderItems items = controlPanel.Items();
  212.             foreach (Shell32.FolderItem item in items)
  213.             {
  214.                 if (item.Name == "网络连接")
  215.                     return (Shell32.Folder)item.GetFolder;
  216.             }
  217.             return null;
  218.         }
  219.         /// 
  220.         /// Gets the network connection with the specified name from the specified shell folder.
  221.         /// 
  222.         /// The Network Connections folder.
  223.         /// The name of the network connection.
  224.         /// The FolderItem for the network connection, or null if it was not found.
  225.         static Shell32.FolderItem2 GetNetworkConnection(Shell32.Folder networkConnectionsFolder, string connectionName)
  226.         {
  227.             Shell32.FolderItems items = networkConnectionsFolder.Items();
  228.             foreach (Shell32.FolderItem2 item in items)
  229.             {
  230.                 if (item.Name == "本地连接")
  231.                 {
  232.                     return item;
  233.                 }
  234.             }
  235.             return null;
  236.         }
  237.         /// 
  238.         /// Gets whether or not the network connection is enabled and the command to enable/disable it.
  239.         /// 
  240.         /// The network connection to check.
  241.         /// On return, receives the verb used to enable or disable the connection.
  242.         /// True if the connection is enabled, false if it is disabled.
  243.         static bool IsNetworkConnectionEnabled(Shell32.FolderItem2 networkConnection, out Shell32.FolderItemVerb enableDisableVerb)
  244.         {
  245.             Shell32.FolderItemVerbs verbs = networkConnection.Verbs();
  246.             foreach (Shell32.FolderItemVerb verb in verbs)
  247.             {
  248.                 if (verb.Name == "启用(&A)")
  249.                 {
  250.                     enableDisableVerb = verb;
  251.                     return false;
  252.                 }
  253.                 else if (verb.Name == "停用(&B)")
  254.                 {
  255.                     enableDisableVerb = verb;
  256.                     return true;
  257.                 }
  258.             }
  259.             throw new ArgumentException("No enable or disable verb found.");
  260.         }
  261.         #endregion
  262.     }
  263. }

你可能感兴趣的:(.Net/C#)