SoFunction
Updated on 2025-03-07

C# Modify the instance of MAC address class


using System;
using ;
using ;
using ;
using Microsoft.Win32;
using ;
using ;
using ;
using ;
using NETCONLib;
namespace DynamicMAC
{
    public class MACHelper
    {
        [DllImport("")]
        private extern static bool InternetGetConnectedState(int Description, int ReservedValue);
        /// <summary>
/// Whether it can be connected to the Internet
        /// </summary>
        /// <returns></returns>
        public bool IsConnectedToInternet()
        {
            int Desc = 0;
            return InternetGetConnectedState(Desc, 0);
        }
        /// <summary>
/// Get the MAC address
        /// </summary>
        public string GetMACAddress()
        {
//Get the registry key of MAC
            RegistryKey macRegistry = ("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control")
                .OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}");
            IList<string> list = ().ToList();
            IPGlobalProperties computerProperties = ();
            NetworkInterface[] nics = ();
var adapter = (o => == "local connection");
            if (adapter == null)
                return null;
            return ;
        }
        /// <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;
//Get the registry key of MAC
            RegistryKey macRegistry = ("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control")
                .OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}").OpenSubKey(index, true);
            if ((newMac))
            {
                ("NetworkAddress");
            }
            else
            {
                ("NetworkAddress", newMac);
                ("Ndi", true).OpenSubKey("params", true).OpenSubKey("NetworkAddress", true).SetValue("Default", newMac);
                ("Ndi", true).OpenSubKey("params", true).OpenSubKey("NetworkAddress", true).SetValue("ParamDesc", "Network Address");
            }
            Thread oThread = new Thread(new ThreadStart(ReConnect));//new Thread to ReConnect
            ();
        }
        /// <summary>
///Reset the MAC address
        /// </summary>
        public void ResetMACAddress()
        {
            SetMACAddress();
        }
        /// <summary>
/// Reconnect
        /// </summary>
        private void ReConnect()
        {
            NetSharingManagerClass netSharingMgr = new NetSharingManagerClass();
            INetSharingEveryConnectionCollection connections = ;
            foreach (INetConnection connection in connections)
            {
                INetConnectionProps connProps = netSharingMgr.get_NetConnectionProps(connection);
                if ( == tagNETCON_MEDIATYPE.NCM_LAN)
                {
(); //Disable the network
();                        ();    //Enable the network
                }
            }
        }
        /// <summary>
/// Generate random MAC address
        /// </summary>
        /// <returns></returns>
        public string CreateNewMacAddress()
        {
            //return "0016D3B5C493";
            int min = 0;
            int max = 16;
            Random ro = new Random();
            var sn = ("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}",
               (min, max).ToString("x"),//0
               (min, max).ToString("x"),//
               (min, max).ToString("x"),
               (min, max).ToString("x"),
               (min, max).ToString("x"),
               (min, max).ToString("x"),//5
               (min, max).ToString("x"),
               (min, max).ToString("x"),
               (min, max).ToString("x"),
               (min, max).ToString("x"),
               (min, max).ToString("x"),//10
               (min, max).ToString("x")
                ).ToUpper();
            return sn;
        }
        /// <summary>
/// Get the corresponding Index of Mac address and registry
        /// </summary>
        /// <param name="macAddress"></param>
        /// <returns></returns>
        public string GetAdapterIndex(out string macAddress)
        {
            ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection colMObj = ();
            macAddress = ;
            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 == )
                return null;
            else
                return ().PadLeft(4, '0');
        }
        #region Temp
        public void noting()
        {
            //ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementClass oMClass = new ManagementClass("Win32_NetworkAdapter");
            ManagementObjectCollection colMObj = ();
            foreach (ManagementObject objMO in colMObj)
            {
                if (objMO["MacAddress"] != null)
                {
                    if (objMO["Name"] != null)
                    {
                        //("Reset", null);
                        ("Disable", null);//Vista only
                        ("Enable", null);//Vista only
                    }
                    //if ((bool)objMO["IPEnabled"] == true)
                    //{
                    //    //(objMO["MacAddress"].ToString());
                    //    //("MacAddress", CreateNewMacAddress());
                    //    //objMO["MacAddress"] = CreateNewMacAddress();
                    //    //("Disable", null);
                    //    //("Enable", null);
                    //    //();
                    //    var iObj = ("EnableDHCP");
                    //    var oObj = ("ReleaseDHCPLease", null, null);
                    //    (100);
                    //    ("RenewDHCPLease", null, null);
                    //}
                }
            }
        }
        public void no()
        {
            networkConnectionsFolder = GetNetworkConnectionsFolder();
            if (networkConnectionsFolder == null)
            {
                ("Network connections folder not found.");
                return;
            }
            Shell32.FolderItem2 networkConnection = GetNetworkConnection(networkConnectionsFolder, );
            if (networkConnection == null)
            {
                ("Network connection not found.");
                return;
            }
            verb;
            try
            {
                IsNetworkConnectionEnabled(networkConnection, out verb);
                ();
                (1000);
                IsNetworkConnectionEnabled(networkConnection, out verb);
                ();
            }
            catch (ArgumentException ex)
            {
                ();
            }
        }
        /// <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 GetNetworkConnectionsFolder()
        {
            sh = new ();
            controlPanel = (3); // Control panel
            items = ();
            foreach ( item in items)
            {
if ( == "Network Connection")
                    return ();
            }
            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( networkConnectionsFolder, string connectionName)
        {
            items = ();
            foreach (Shell32.FolderItem2 item in items)
            {
if ( == "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, 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 enableDisableVerb)
        {
            verbs = ();
            foreach ( verb in verbs)
            {
if ( == "Enable (&A)")
                {
                    enableDisableVerb = verb;
                    return false;
                }
else if ( == "&Disable(&B)")
                {
                    enableDisableVerb = verb;
                    return true;
                }
            }
            throw new ArgumentException("No enable or disable verb found.");
        }
        #endregion
    }
}