1. Update the MAC address
Add the key value in the registry to the MAC address
2. reconnect to the network
I tried three methods:
ManagementClass provides the Disable and Enable methods, but only supports the Vista operating system.
The Shell. dll method can be implemented, but it is annoying to handle it. In addition, the prompt box "starting" is displayed during the reconnection, Which is unfriendly.
The Disconnect and Connect methods of NetSharingManagerClass can be implemented, but one problem is that the IP address will be updated again, obviously.
Copy codeThe Code is as follows: 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>
/// Whether to connect to the Internet
/// </Summary>
/// <Returns> </returns>
Public bool IsConnectedToInternet ()
{
Int Desc = 0;
Return InternetGetConnectedState (Desc, 0 );
}
/// <Summary>
/// Obtain the MAC address
/// </Summary>
Public string GetMACAddress ()
{
// Obtain the MAC registry key
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 [] interfaces = NetworkInterface. GetAllNetworkInterfaces ();
Var adapter = callback. First (o => o. Name = "Local Connection ");
If (adapter = null)
Return null;
Return string. Empty;
}
/// <Summary>
/// Set the MAC address
/// </Summary>
/// <Param name = "newMac"> </param>
Public void SetMACAddress (string newMac)
{
String macAddress;
String index = GetAdapterIndex (out macAddress );
If (index = null)
Return;
// Obtain the MAC registry key
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>
/// Reset the MAC address
/// </Summary>
Public void ResetMACAddress ()
{
SetMACAddress (string. Empty );
}
/// <Summary>
/// Reconnect
/// </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 (); // disable the network
Connection. Connect (); // enable the network
}
}
}
/// <Summary>
/// Generate a random MAC address
/// </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>
/// Obtain the Mac address and the corresponding Index of the Registry.
/// </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;
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 = "network connection ")
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 = "Local Connection ")
{
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, attributes es 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 in verbs)
{
If (verb. Name = "enable (& )")
{
EnableDisableVerb = verb;
Return false;
}
Else if (verb. Name = "disabled (& B )")
{
EnableDisableVerb = verb;
Return true;
}
}
Throw new ArgumentException ("No enable or disable verb found .");
}
# Endregion
}
}