C#修改MAC地址类的实例_C#教程

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
    }
}

时间: 2024-09-10 10:02:19

C#修改MAC地址类的实例_C#教程的相关文章

C#获取路由器外网IP,MAC地址的实现代码_C#教程

C#实现的获取路由器MAC地址,路由器外网地址.对于要获取路由器MAC地址,一定需要知道路由器web管理系统的用户名和密码.至于获取路由器的外网IP地址,可以不需要知道路由器web管理系统的用户名和密码,但是需要有一个代理页面获取客户端公网ip地址的,这样C#请求此页面即可获取到路由器公网ip地址.如 //getip.ashx 测试路由为水星 MR804,水星 MR808,都可以成功重启路由和获取到路由器MAC和外网IP地址 源代码 using System.Text; using System

C#实现DataSet内数据转化为Excel和Word文件的通用类完整实例_C#教程

本文实例讲述了C#实现DataSet内数据转化为Excel和Word文件的通用类.分享给大家供大家参考,具体如下: 前不久因为项目的需要写的一个C#把DataSet内数据转化为Excel和Word文件的通用类,这些关于Excel.Word的导出方法,基本可以实现日常须要,其中有些方法可以把数据导出后 生成Xml格式,再导入数据库!有些屏蔽内容没有去掉,保留下来方便学习参考用之. 最后请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性. using Syste

C#实现可捕获几乎所有键盘鼠标事件的钩子类完整实例_C#教程

本文实例讲述了C#实现可捕获几乎所有键盘鼠标事件的钩子类.分享给大家供大家参考,具体如下: using System; using System.Text; using System.Runtime.InteropServices; using System.Reflection; using System.Windows.Forms; namespace MouseKeyboardLibrary { /// <summary> /// Abstract base class for Mous

C#实现的xml操作类完整实例_C#教程

本文实例讲述了C#实现的xml操作类,分享给大家供大家参考,具体如下: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System

用C#获取硬盘序列号,CPU序列号,网卡MAC地址的源码_C#教程

privatestring[]GetMoc() { string[]str=newstring[3]; ManagementClassmcCpu=newManagementClass("win32_Processor"); ManagementObjectCollectionmocCpu=mcCpu.GetInstances(); foreach(ManagementObjectminmocCpu) { str[0]=m["ProcessorId"].ToStrin

修改mac地址图解教程

如何修改mac地址?很简单! 有些场合,例如冒充网络中的正式用户,就需要修改你的网卡MAC.要修改MAC地址,你可以通过硬件的方法实现,即利用网卡厂家提供的修改程序来烧录网卡的EEPROM,这样做虽然可行,但是风险很大.操作也复杂,即使你很有经验,也难免在操作中出现错误. 其实你完全没必要用烧录方法.修改网卡中的MAC地址.要知道Windows安装的时候,会自动从网卡中读入MAC地址,把它存放在注册表中以备后用.当数据在网络中传输时,从网卡发出的数据包中要求有一个源MAC地址,这个MAC地址就是

win7系统无法修改MAC地址怎么办?

win7系统无法修改MAC地址怎么办? 和往常一样,咱们首先分析一下问题出现的原因:无线网卡的Mac地址突然无法修改了,有可能是大家对于Mac的修改方法不是很了解,一般来说,Mac的修改只有A.E的可以修改,其他的都不行. 解决方法: 1.首先,咱们可以先对系统进行备份,然后准备好同系列的无线网卡驱动备份. 2.接下来,咱们返回到桌面界面,然后右键点击计算机图标,选择管理. 3.在打开的计算机管理界面中,咱们单击左侧菜单中的设备管理器,然后找到无线网卡并右键点击,选择更新驱动程序. 4.之后咱们

win7系统vmware虚拟机怎么修改mac地址

  win7系统vmware虚拟机怎么修改mac地址 1.打开虚拟机,点击"编辑虚拟机设置"; 2.分别点击 "硬件""网络适配器""高级",然后就可以对网卡的MAC地址进行操作了; 3.你可以随意更改MAC地址,更改后,确定保存后,就会生效,启动电脑后,就会用新的MAC地址.

Windows系统修改MAC地址方法

1.在"HKEY_LOCAL_MACHINESYSTEMCurrentControlSetControlClass4D36E972- E325-11CE-BFC1-08002BE10318000.0001.0002"等主键下, 因为你有可能安装了不止一块网卡,所以在这个主键下可能会有多个类似于"0000.0001"的主键,这时候你可以查找DriverDesc内容为你要修改的网卡的描述相吻合的主键,如"0001". 2.在上面提到的主键下,添一个字