[C#]修改MAC地址類的實例
1.更新MAC地址
將註冊表中的鍵值添加上MAC地址
2.重新連接網絡
試過了3個方法:
- ManagementClass最新提供了Disable,Enable方法,但只支持Vista操作系統
- Shell.dll的方法,可以實現,但處理起來很煩,另外在重新連接時顯示“啟動中”提示框,不友好。
- NetSharingManagerClass 的Disconnect, Connect方法,可以實現,但有一個問題是,會重新更新IP地址,有明顯感覺等。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Net.NetworkInformation;
using System.Management;
using System.Threading;
using System.Runtime.InteropServices;
using NETCONLib;
namespace DynamicMAC
{
public class MACHelper
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(int Description, int ReservedValue);
/// <summary>
/// 是否能連接上Internet
/// </summary>
/// <returns></returns>
public bool IsConnectedToInternet()
{
int Desc = 0;
return InternetGetConnectedState(Desc, 0);
}
/// <summary>
/// 獲取MAC地址
/// </summary>
public string GetMACAddress()
{
//得到 MAC的註冊表鍵
RegistryKey macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control")
.OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}");
IList<string> list = macRegistry.GetSubKeyNames().ToList();
IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
var adapter = nics.First(o => o.Name == "本地連接");
if (adapter == null)
return null;
return string.Empty;
}
/// <summary>
/// 設置MAC地址
/// </summary>
/// <param name="newMac"></param>
public void SetMACAddress(string newMac)
{
string macAddress;
string index = GetAdapterIndex(out macAddress);
if (index == null)
return;
//得到 MAC的註冊表鍵
RegistryKey macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control")
.OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}").OpenSubKey(index, true);
if (string.IsNullOrEmpty(newMac))
{
macRegistry.DeleteValue("NetworkAddress");
}
else
{
macRegistry.SetValue("NetworkAddress", newMac);
macRegistry.OpenSubKey("Ndi", true).OpenSubKey("params", true).OpenSubKey("NetworkAddress", true).SetValue("Default", newMac);
macRegistry.OpenSubKey("Ndi", true).OpenSubKey("params", true).OpenSubKey("NetworkAddress", true).SetValue("ParamDesc", "Network Address");
}
Thread oThread = new Thread(new ThreadStart(ReConnect));//new Thread to ReConnect
oThread.Start();
}
/// <summary>
/// 重設MAC地址
/// </summary>
public void ResetMACAddress()
{
SetMACAddress(string.Empty);
}
/// <summary>
/// 重新連接
/// </summary>
private void ReConnect()
{
NetSharingManagerClass netSharingMgr = new NetSharingManagerClass();
INetSharingEveryConnectionCollection connections = netSharingMgr.EnumEveryConnection;
foreach (INetConnection connection in connections)
{
INetConnectionProps connProps = netSharingMgr.get_NetConnectionProps(connection);
if (connProps.MediaType == tagNETCON_MEDIATYPE.NCM_LAN)
{
connection.Disconnect(); //禁用網絡
connection.Connect(); //啟用網絡
}
}
}
/// <summary>
/// 生成隨機MAC地址
/// </summary>
/// <returns></returns>
public string CreateNewMacAddress()
{
//return "0016D3B5C493";
int min = 0;
int max = 16;
Random ro = new Random();
var sn = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}",
ro.Next(min, max).ToString("x"),//0
ro.Next(min, max).ToString("x"),//
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),//5
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),//10
ro.Next(min, max).ToString("x")
).ToUpper();
return sn;
}
/// <summary>
/// 得到Mac地址及註冊表對應Index
/// </summary>
/// <param name="macAddress"></param>
/// <returns></returns>
public string GetAdapterIndex(out string macAddress)
{
ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection colMObj = oMClass.GetInstances();
macAddress = string.Empty;
int indexString = 1;
foreach (ManagementObject objMO in colMObj)
{
indexString++;
if (objMO["MacAddress"] != null && (bool)objMO["IPEnabled"] == true)
{
macAddress = objMO["MacAddress"].ToString().Replace(":", "");
break;
}
}
if (macAddress == string.Empty)
return null;
else
return indexString.ToString().PadLeft(4, '0');
}
#region Temp
public void noting()
{
//ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapter");
ManagementObjectCollection colMObj = oMClass.GetInstances();
foreach (ManagementObject objMO in colMObj)
{
if (objMO["MacAddress"] != null)
{
if (objMO["Name"] != null)
{
//objMO.InvokeMethod("Reset", null);
objMO.InvokeMethod("Disable", null);//Vista only
objMO.InvokeMethod("Enable", null);//Vista only
}
//if ((bool)objMO["IPEnabled"] == true)
//{
// //Console.WriteLine(objMO["MacAddress"].ToString());
// //objMO.SetPropertyValue("MacAddress", CreateNewMacAddress());
// //objMO["MacAddress"] = CreateNewMacAddress();
// //objMO.InvokeMethod("Disable", null);
// //objMO.InvokeMethod("Enable", null);
// //objMO.Path.ReleaseDHCPLease();
// var iObj = objMO.GetMethodParameters("EnableDHCP");
// var oObj = objMO.InvokeMethod("ReleaseDHCPLease", null, null);
// Thread.Sleep(100);
// objMO.InvokeMethod("RenewDHCPLease", null, null);
//}
}
}
}
public void no()
{
Shell32.Folder networkConnectionsFolder = GetNetworkConnectionsFolder();
if (networkConnectionsFolder == null)
{
Console.WriteLine("Network connections folder not found.");
return;
}
Shell32.FolderItem2 networkConnection = GetNetworkConnection(networkConnectionsFolder, string.Empty);
if (networkConnection == null)
{
Console.WriteLine("Network connection not found.");
return;
}
Shell32.FolderItemVerb verb;
try
{
IsNetworkConnectionEnabled(networkConnection, out verb);
verb.DoIt();
Thread.Sleep(1000);
IsNetworkConnectionEnabled(networkConnection, out verb);
verb.DoIt();
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// Gets the Network Connections folder in the control panel.
/// </summary>
/// <returns>The Folder for the Network Connections folder, or null if it was not found.</returns>
static Shell32.Folder GetNetworkConnectionsFolder()
{
Shell32.Shell sh = new Shell32.Shell();
Shell32.Folder controlPanel = sh.NameSpace(3); // Control panel
Shell32.FolderItems items = controlPanel.Items();
foreach (Shell32.FolderItem item in items)
{
if (item.Name == "網絡連接")
return (Shell32.Folder)item.GetFolder;
}
return null;
}
/// <summary>
/// Gets the network connection with the specified name from the specified shell folder.
/// </summary>
/// <param name="networkConnectionsFolder">The Network Connections folder.</param>
/// <param name="connectionName">The name of the network connection.</param>
/// <returns>The FolderItem for the network connection, or null if it was not found.</returns>
static Shell32.FolderItem2 GetNetworkConnection(Shell32.Folder networkConnectionsFolder, string connectionName)
{
Shell32.FolderItems items = networkConnectionsFolder.Items();
foreach (Shell32.FolderItem2 item in items)
{
if (item.Name == "本地連接")
{
return item;
}
}
return null;
}
/// <summary>
/// Gets whether or not the network connection is enabled and the command to enable/disable it.
/// </summary>
/// <param name="networkConnection">The network connection to check.</param>
/// <param name="enableDisableVerb">On return, receives the verb used to enable or disable the connection.</param>
/// <returns>True if the connection is enabled, false if it is disabled.</returns>
static bool IsNetworkConnectionEnabled(Shell32.FolderItem2 networkConnection, out Shell32.FolderItemVerb enableDisableVerb)
{
Shell32.FolderItemVerbs verbs = networkConnection.Verbs();
foreach (Shell32.FolderItemVerb verb in verbs)
{
if (verb.Name == "啟用(&A)")
{
enableDisableVerb = verb;
return false;
}
else if (verb.Name == "停用(&B)")
{
enableDisableVerb = verb;
return true;
}
}
throw new ArgumentException("No enable or disable verb found.");
}
#endregion
}
}
這裏面Mac地址是通過改變註冊表編輯器的內容來改變的.具體註冊表地址在計算機\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\000?
然後000? 裏面有個DriverDesc 看這個是不是你的驅動器版本驗證,如果都對就是這個,然後裏面有個NetworkAddress 屬性,如果沒有手動添加一個.然後他前6位最好不要變.只改後面的。
將註冊表中的鍵值添加上MAC地址
2.重新連接網絡
試過了3個方法:
- ManagementClass最新提供了Disable,Enable方法,但只支持Vista操作系統
- Shell.dll的方法,可以實現,但處理起來很煩,另外在重新連接時顯示“啟動中”提示框,不友好。
- NetSharingManagerClass 的Disconnect, Connect方法,可以實現,但有一個問題是,會重新更新IP地址,有明顯感覺等。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Net.NetworkInformation;
using System.Management;
using System.Threading;
using System.Runtime.InteropServices;
using NETCONLib;
namespace DynamicMAC
{
public class MACHelper
{
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(int Description, int ReservedValue);
/// <summary>
/// 是否能連接上Internet
/// </summary>
/// <returns></returns>
public bool IsConnectedToInternet()
{
int Desc = 0;
return InternetGetConnectedState(Desc, 0);
}
/// <summary>
/// 獲取MAC地址
/// </summary>
public string GetMACAddress()
{
//得到 MAC的註冊表鍵
RegistryKey macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control")
.OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}");
IList<string> list = macRegistry.GetSubKeyNames().ToList();
IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties();
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
var adapter = nics.First(o => o.Name == "本地連接");
if (adapter == null)
return null;
return string.Empty;
}
/// <summary>
/// 設置MAC地址
/// </summary>
/// <param name="newMac"></param>
public void SetMACAddress(string newMac)
{
string macAddress;
string index = GetAdapterIndex(out macAddress);
if (index == null)
return;
//得到 MAC的註冊表鍵
RegistryKey macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control")
.OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}").OpenSubKey(index, true);
if (string.IsNullOrEmpty(newMac))
{
macRegistry.DeleteValue("NetworkAddress");
}
else
{
macRegistry.SetValue("NetworkAddress", newMac);
macRegistry.OpenSubKey("Ndi", true).OpenSubKey("params", true).OpenSubKey("NetworkAddress", true).SetValue("Default", newMac);
macRegistry.OpenSubKey("Ndi", true).OpenSubKey("params", true).OpenSubKey("NetworkAddress", true).SetValue("ParamDesc", "Network Address");
}
Thread oThread = new Thread(new ThreadStart(ReConnect));//new Thread to ReConnect
oThread.Start();
}
/// <summary>
/// 重設MAC地址
/// </summary>
public void ResetMACAddress()
{
SetMACAddress(string.Empty);
}
/// <summary>
/// 重新連接
/// </summary>
private void ReConnect()
{
NetSharingManagerClass netSharingMgr = new NetSharingManagerClass();
INetSharingEveryConnectionCollection connections = netSharingMgr.EnumEveryConnection;
foreach (INetConnection connection in connections)
{
INetConnectionProps connProps = netSharingMgr.get_NetConnectionProps(connection);
if (connProps.MediaType == tagNETCON_MEDIATYPE.NCM_LAN)
{
connection.Disconnect(); //禁用網絡
connection.Connect(); //啟用網絡
}
}
}
/// <summary>
/// 生成隨機MAC地址
/// </summary>
/// <returns></returns>
public string CreateNewMacAddress()
{
//return "0016D3B5C493";
int min = 0;
int max = 16;
Random ro = new Random();
var sn = string.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}",
ro.Next(min, max).ToString("x"),//0
ro.Next(min, max).ToString("x"),//
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),//5
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),
ro.Next(min, max).ToString("x"),//10
ro.Next(min, max).ToString("x")
).ToUpper();
return sn;
}
/// <summary>
/// 得到Mac地址及註冊表對應Index
/// </summary>
/// <param name="macAddress"></param>
/// <returns></returns>
public string GetAdapterIndex(out string macAddress)
{
ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection colMObj = oMClass.GetInstances();
macAddress = string.Empty;
int indexString = 1;
foreach (ManagementObject objMO in colMObj)
{
indexString++;
if (objMO["MacAddress"] != null && (bool)objMO["IPEnabled"] == true)
{
macAddress = objMO["MacAddress"].ToString().Replace(":", "");
break;
}
}
if (macAddress == string.Empty)
return null;
else
return indexString.ToString().PadLeft(4, '0');
}
#region Temp
public void noting()
{
//ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapter");
ManagementObjectCollection colMObj = oMClass.GetInstances();
foreach (ManagementObject objMO in colMObj)
{
if (objMO["MacAddress"] != null)
{
if (objMO["Name"] != null)
{
//objMO.InvokeMethod("Reset", null);
objMO.InvokeMethod("Disable", null);//Vista only
objMO.InvokeMethod("Enable", null);//Vista only
}
//if ((bool)objMO["IPEnabled"] == true)
//{
// //Console.WriteLine(objMO["MacAddress"].ToString());
// //objMO.SetPropertyValue("MacAddress", CreateNewMacAddress());
// //objMO["MacAddress"] = CreateNewMacAddress();
// //objMO.InvokeMethod("Disable", null);
// //objMO.InvokeMethod("Enable", null);
// //objMO.Path.ReleaseDHCPLease();
// var iObj = objMO.GetMethodParameters("EnableDHCP");
// var oObj = objMO.InvokeMethod("ReleaseDHCPLease", null, null);
// Thread.Sleep(100);
// objMO.InvokeMethod("RenewDHCPLease", null, null);
//}
}
}
}
public void no()
{
Shell32.Folder networkConnectionsFolder = GetNetworkConnectionsFolder();
if (networkConnectionsFolder == null)
{
Console.WriteLine("Network connections folder not found.");
return;
}
Shell32.FolderItem2 networkConnection = GetNetworkConnection(networkConnectionsFolder, string.Empty);
if (networkConnection == null)
{
Console.WriteLine("Network connection not found.");
return;
}
Shell32.FolderItemVerb verb;
try
{
IsNetworkConnectionEnabled(networkConnection, out verb);
verb.DoIt();
Thread.Sleep(1000);
IsNetworkConnectionEnabled(networkConnection, out verb);
verb.DoIt();
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// Gets the Network Connections folder in the control panel.
/// </summary>
/// <returns>The Folder for the Network Connections folder, or null if it was not found.</returns>
static Shell32.Folder GetNetworkConnectionsFolder()
{
Shell32.Shell sh = new Shell32.Shell();
Shell32.Folder controlPanel = sh.NameSpace(3); // Control panel
Shell32.FolderItems items = controlPanel.Items();
foreach (Shell32.FolderItem item in items)
{
if (item.Name == "網絡連接")
return (Shell32.Folder)item.GetFolder;
}
return null;
}
/// <summary>
/// Gets the network connection with the specified name from the specified shell folder.
/// </summary>
/// <param name="networkConnectionsFolder">The Network Connections folder.</param>
/// <param name="connectionName">The name of the network connection.</param>
/// <returns>The FolderItem for the network connection, or null if it was not found.</returns>
static Shell32.FolderItem2 GetNetworkConnection(Shell32.Folder networkConnectionsFolder, string connectionName)
{
Shell32.FolderItems items = networkConnectionsFolder.Items();
foreach (Shell32.FolderItem2 item in items)
{
if (item.Name == "本地連接")
{
return item;
}
}
return null;
}
/// <summary>
/// Gets whether or not the network connection is enabled and the command to enable/disable it.
/// </summary>
/// <param name="networkConnection">The network connection to check.</param>
/// <param name="enableDisableVerb">On return, receives the verb used to enable or disable the connection.</param>
/// <returns>True if the connection is enabled, false if it is disabled.</returns>
static bool IsNetworkConnectionEnabled(Shell32.FolderItem2 networkConnection, out Shell32.FolderItemVerb enableDisableVerb)
{
Shell32.FolderItemVerbs verbs = networkConnection.Verbs();
foreach (Shell32.FolderItemVerb verb in verbs)
{
if (verb.Name == "啟用(&A)")
{
enableDisableVerb = verb;
return false;
}
else if (verb.Name == "停用(&B)")
{
enableDisableVerb = verb;
return true;
}
}
throw new ArgumentException("No enable or disable verb found.");
}
#endregion
}
}
這裏面Mac地址是通過改變註冊表編輯器的內容來改變的.具體註冊表地址在計算機\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\000?
然後000? 裏面有個DriverDesc 看這個是不是你的驅動器版本驗證,如果都對就是這個,然後裏面有個NetworkAddress 屬性,如果沒有手動添加一個.然後他前6位最好不要變.只改後面的。
留言
張貼留言