欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#修改MAC地址类的实例

程序员文章站 2023-12-04 16:04:58
1.更新mac地址   将注册表中的键值添加上mac地址 2.重新连接网络  试过了3个方法:   managementclas...

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