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. /// <summary>
  18. /// 是否能连接上Internet
  19. /// </summary>
  20. /// <returns></returns>
  21. public bool IsConnectedToInternet()
  22. {
  23. int Desc = 0;
  24. return InternetGetConnectedState(Desc, 0);
  25. }
  26. /// <summary>
  27. /// 获取MAC地址
  28. /// </summary>
  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. /// <summary>
  43. /// 设置MAC地址
  44. /// </summary>
  45. /// <param name="newMac"></param>
  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. /// <summary>
  69. /// 重设MAC地址
  70. /// </summary>
  71. public void ResetMACAddress()
  72. {
  73. SetMACAddress(string.Empty);
  74. }
  75. /// <summary>
  76. /// 重新连接
  77. /// </summary>
  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. /// <summary>
  93. /// 生成随机MAC地址
  94. /// </summary>
  95. /// <returns></returns>
  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. /// <summary>
  119. /// 得到Mac地址及注册表对应Index
  120. /// </summary>
  121. /// <param name="macAddress"></param>
  122. /// <returns></returns>
  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. /// <summary>
  204. /// Gets the Network Connections folder in the control panel.
  205. /// </summary>
  206. /// <returns>The Folder for the Network Connections folder, or null if it was not found.</returns>
  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. /// <summary>
  220. /// Gets the network connection with the specified name from the specified shell folder.
  221. /// </summary>
  222. /// <param name="networkConnectionsFolder">The Network Connections folder.</param>
  223. /// <param name="connectionName">The name of the network connection.</param>
  224. /// <returns>The FolderItem for the network connection, or null if it was not found.</returns>
  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. /// <summary>
  238. /// Gets whether or not the network connection is enabled and the command to enable/disable it.
  239. /// </summary>
  240. /// <param name="networkConnection">The network connection to check.</param>
  241. /// <param name="enableDisableVerb">On return, receives the verb used to enable or disable the connection.</param>
  242. /// <returns>True if the connection is enabled, false if it is disabled.</returns>
  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. }

Mac地址自动生成器核心处理类相关推荐

  1. 自动更改mac地址 ip计算机名的软件,根据MAC地址自动更改计算机名IP的批处理

    根据MAC地址自动更改计算机名IP的批处理 根据MAC地址自动更改计算机名IP的批处理 一些错误信息的解决方法: 1.C:\>wmic path win32_pnpsigneddriver 节点 ...

  2. 【瑞芯微Rockchip Linux平台】SoftAp需求实现(3)动态获取BT Mac地址并更新beacon帧中的mac信息

    [瑞芯微Rockchip Linux平台]SoftAp需求实现(3)动态获取BT Mac地址并更新beacon帧中的mac信息 1. 获取本机的蓝牙mac地址 __get_bt_mac_addr() ...

  3. 华为数通笔记-MAC地址

    MAC简介 MAC基本概念 MAC(Media Access Control)地址用来定义网络设备的位置.MAC地址由48比特长.12位的16进制数字组成,其中从左到右开始,0到23bit是厂商向IE ...

  4. linux绑定ip mac地址,dhcpd mac地址绑定ip地址

    今天突然想起,之前的cobbler装系统还是有些不足之处: 用koan装完系统之后还是需要再次手动配置一遍ip地址,感觉还是不太方便,所以研究了下dhcp的另一个功能,就是根据mac地址自动分配固定的 ...

  5. 启明云端分享|sigmastar SSD201/ssd202核心板升级参考,可实现开机自动从 SD 卡升级固件或开机自动从 SD 卡烧录 MAC 地址

    实现功能 1.开机自动从 SD 卡升级固件: 2.开机自动从 SD 卡烧录 MAC 地址: 一.实现方法 自动升级固件 示例:# vi project/image/configs/i2m/script ...

  6. linux脚本怎么把文件地址变成动态地址,Linux脚本程序自动修改网卡配置文件中的MAC地址...

    在玩Linux虚拟机的时候,一个安装好linux系统的virtual HDD会用于创建多个虚拟机,这样就不需要在创建每个虚拟机都安装一遍系统了.virtual HDD加载到虚拟机后,新的虚拟机的MAC ...

  7. linux脚本自动修改网卡,Linux脚本程序自动修改网卡配置文件中的MAC地址

    在玩Linux虚拟机的时候,一个安装好linux系统的virtual HDD会用于创建多个虚拟机,这样就不需要在创建每个虚拟机都安装一遍系统了.virtual HDD加载到虚拟机后,新的虚拟机的MAC ...

  8. 启明云端分享|SSD201_自动升级固件与烧录MAC地址

    实现功能 1.开机自动从SD卡升级固件: 2.开机自动从SD卡烧录MAC地址: 实现方法 自动升级固件 vi project/image/configs/i2m/script_nand.mk @ech ...

  9. java自动获取ip_java自动获取电脑ip和MAC地址

    java自动获取电脑ip和MAC地址 利用getLocalHost获得计算机名称和ip getByInetAddress可以确定一个IP地址属于哪一个网络接口,这个IP地址通过命令行参数传入 用get ...

最新文章

  1. Asp.Net 使用 GDI+ 绘制3D饼图入门篇源码
  2. 5 修改request对象变量_【总结】前端5大常见设计模式,代码一看你就懂!
  3. 寒冰linux视频教程笔记8 系统监控
  4. msm8909相关事宜
  5. 王牌之作 特斯拉国产Model Y明年初下线
  6. 插入区间Python解法
  7. Linux工作笔记-根据PID查询进程是否存在(进程管理相关程序中常用)
  8. Python如何在循环语句中加入两个变量_Python基础知识
  9. kotlin之高阶函数
  10. 整数规划 Integer Programming 是什么
  11. HTML 标签的 target 属性
  12. 《威胁建模:设计和交付更安全的软件》——3.11 小结
  13. 电脑上没有iis组件,怎么才能安装iis?
  14. P2P中DHT网络介绍
  15. 华为手机信息不弹屏了为什么_华为手机顶部消息弹窗怎么关闭?
  16. 每天一个小技巧(新建桌面)
  17. ios播放器横竖屏切换的问题
  18. Android扫一扫 有仿微信版
  19. 数据库原理与技术(专升本)-含答案
  20. 大数据导论答案_2020高校邦《数据科学与大数据技术导论》课后作业答案

热门文章

  1. java实现fcfs_模拟实现FCFS(先来先服务)算法
  2. 穷人冲冲冲:为什么总是“坏人”赚钱?
  3. UOS如何添加window字体或者非商业字体
  4. DHCP静态绑定和ARP静态绑定
  5. VS插件_Supercharger_Magic Comments_Seperator Lines 增加分割线
  6. SpringCloud04-Ribbon、OpenFeign、Hystrix
  7. 怎么把PPT文件转换成Word?这样转换轻松办到
  8. 海外服务器受到攻击如何增加防御
  9. ECharts——条形图
  10. SQLserver中建立外键时显示引用了无效的表