当前位置:  编程技术>.net/c#/asp.net

C#修改MAC地址类的实例

    来源: 互联网  发布时间:2014-10-17

    本文导语:  1.更新MAC地址   将注册表中的键值添加上MAC地址 2.重新连接网络  试过了3个方法:   ManagementClass最新提供了Disable,Enable方法,但只支持Vista操作系统   Shell.dll的方法,可以实现,但处理起来很烦,另外在重新连接时显示“启动...

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);
        ///
        /// 是否能连接上Internet
        ///
        ///
        public bool IsConnectedToInternet()
        {
            int Desc = 0;
            return InternetGetConnectedState(Desc, 0);
        }
        ///
        /// 获取MAC地址
        ///
        public string GetMACAddress()
        {
            //得到 MAC的注册表键
            RegistryKey macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM").OpenSubKey("CurrentControlSet").OpenSubKey("Control")
                .OpenSubKey("Class").OpenSubKey("{4D36E972-E325-11CE-BFC1-08002bE10318}");
            IList 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;
        }
        ///
        /// 设置MAC地址
        ///
        ///
        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();
        }
        ///
        /// 重设MAC地址
        ///
        public void ResetMACAddress()
        {
            SetMACAddress(string.Empty);
        }
        ///
        /// 重新连接
        ///
        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();    //启用网络
                }
            }
        }
        ///
        /// 生成随机MAC地址
        ///
        ///
        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;
        }
        ///
        /// 得到Mac地址及注册表对应Index
        ///
        ///
        ///
        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);
            }
        }
        ///
        /// Gets the Network Connections folder in the control panel.
        ///
        /// The Folder for the Network Connections folder, or null if it was not found.
        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;
        }
        ///
        /// Gets the network connection with the specified name from the specified shell folder.
        ///
        /// The Network Connections folder.
        /// The name of the network connection.
        /// The FolderItem for the network connection, or null if it was not found.
        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;
        }
        ///
        /// Gets whether or not the network connection is enabled and the command to enable/disable it.
        ///
        /// The network connection to check.
        /// On return, receives the verb used to enable or disable the connection.
        /// True if the connection is enabled, false if it is disabled.
        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
    }
}

    
 
 

您可能感兴趣的文章:

  • C# Timer定时器控件运行时需要修改系统时间的问题
  • c# 多文档窗口修改mdi窗体背景色的实现代码
  • C#切换鼠标左右键习惯无需控制面板中修改
  • C# cmd中修改显示(显示进度变化效果)的方法
  • c#调用qq邮箱smtp发送邮件(修改版)
  • c#代码自动修改解决方案下任意文件实例
  • C#使用非托管代码直接修改字符串的方法
  • c#调用qq邮箱smtp发送邮件修改版代码分享
  • 怎么利用c#修改services的Startup type
  • 通过C#调用cmd来修改服务启动类型
  • C#读取与修改App.Config的实例解析
  • c#操作xml的代码(插入节点、修改节点、删除节点等)
  • fedora 4 下怎么设置/修改dns服务器地址? iis7站长之家
  • c#操作xml的类(创建 添加 修改 删除)
  • Linux操作系统下Oracle数据库多实例启动方式及修改内存
  • jquery修改属性值实例代码(设置属性值)
  • sql server 触发器实例(判断是插入、删除,还是修改)
  • php更新修改excel中的内容实例代码
  • Java批量修改文件名的实例代码
  • 请问String类的实例真的是不能修改(immutable)的吗?
  • Python修改Excel数据的实例代码
  • sql server 触发器实例 创建、删除、修改、查看触发器的例子
  • java怎么创建目录(删除/修改/复制目录及文件)代码实例
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • linux/Centos下查看和修改网卡Mac地址(ifconfig命令)
  • 修改ip地址的话应该修改/ect下哪个文件里的内容?
  • [fedora]下怎么修改MAC地址,并且要重新动的时候还是修改后的值。
  • Ubuntu中修改IP地址为静态地址不成功
  • 怎样修改linux下网卡的MAC地址?
  • 在linux下如何修改ip地址???-调用C函数
  • 用ioctl修改网卡接口eth0的ip地址的问题,请~
  • 如何修改MAC地址???
  • 在redhat8下如何修改网卡mac地址
  • 如何在发送数据的时候,修改IP包里的IP地址,使对方看到的不是自己真实的IP地址?
  • fedora 4 下怎么设置/修改dns服务器地址?
  • 修改ip地址?
  • IP地址修改无法保存
  • linux修改mac地址方法分享
  • 怎么修改mark地址啊
  • 用smit tcpip修改ip地址后,无法保存。
  • 在Solaris 8下怎样才能修改网卡Mac地址???
  • 请教,有什么办法修改ELF文件的可执行地址吗?
  • 请问在linux下怎样修改ip地址!!急,在线等
  • 请教如何在程序中修改机器的IP地址?
  • 修改链接时的搜索地址(简单问题)
  • 修改Windows硬盘分区名称
  • unix 下 C++实现 ftp 到另一台主机上 修改文件内容 !能不能直接在主机上修改 还是只能get下来本地修改完后 在put上去
  • 修改配置真正解决php文件上传大小限制问题(apache+php)
  • 高手帮帮忙!!! 在线等!!outlook的附件修改且保存后,再次打开发现是修改之前的原件
  • 修改配置真正解决php文件上传大小限制问题(nginx+php)
  • 原密码被人恶意修改,如何修改suse系统的超级用户密码(急)
  • mysql中如何查看最大连接数(max_connections)和修改最大连接数
  • 有什么命令可以修改整个目录下文件的最后修改时间?
  • sharepoint 2010中item.Update()和item.SystemUpdate 修改数据版本问题解决
  • 请教一下,如何修改ubuntu命令,使其可以直接修改kvm虚拟机配置


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3