C#修改MAC地址类的实例

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

(0)

相关推荐

  • C#获取机器码的方法详解(机器名,CPU编号,硬盘编号,网卡mac等)

    本文实例讲述了C#获取机器码的方法.分享给大家供大家参考,具体如下: using System.Runtime.InteropServices; using System.Management; using System; public class HardwareInfo { //取机器名 public string GetHostName() { return System.Net.Dns.GetHostName(); } //取CPU编号 public String GetCpuID()

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

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

  • C#利用win32 Api 修改本地系统时间、获取硬盘序列号

    C#利用win32 Api 修改本地系统时间.获取硬盘序列号,可以用于软件注册机制的编写! 复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace Fengyun {     public class Win32     {         #region 修改本地系统时间         [DllIm

  • C#实现获取MAC地址的方法

    本文实例讲述了C#实现获取MAC地址的方法,是一个非常常见而且实用的功能,具体方法如下: 主要功能代码如下: /// <summary> /// 根据网卡类型来获取mac地址 /// </summary> /// <param name="networkType">网卡类型</param> /// <param name="macAddressFormatHanlder">格式化获取到的mac地址</

  • C#获得MAC地址(网卡序列号)的实现代码

    代码如下: 复制代码 代码如下: //获得网卡序列号    public string GetMoAddress()    {        string MoAddress = " ";        ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");        ManagementObjectCollection moc2 = mc.GetInstanc

  • C#获取计算机名,IP,MAC信息实现代码

    利用C#获取计算机名,IP,MAC信息,如下为源代码: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Management; namespace Wenanry.Net { /// <summary> /// 获取计算机系统信息 /// </summary> public class ManagementSyst

  • C#获取CPU编号的方法

    本文实例讲述了C#获取CPU编号的方法.分享给大家供大家参考.具体如下: /// <summary> /// Gets the cpu 编号. ///需引用 using System.Management; /// </summary> /// <returns></returns> public string GetCpuId() { string cpuInfo = ""; ManagementClass cimobject = ne

  • C# 多网卡 Server Listen

    VC和BCB中做一个Server的监听程序,只需要指定端口,然后监听(Listen)就行了.在C#找不到这个函数了,慢慢看MSDN,怎么需要指定IP和Port才能监听,那么多网卡的机器应该怎么写程序呢?下面的程序可以解释怎么去做.  TcpListener 类别会提供简易的方法,用以在封锁的同步模式中聆听 (Listen) 和接受输入的连接要求.您可以使用 TcpClient 或 Socket 来连接 TcpListener .使用 IPEndPoint .本机 IP 地址和连接端口编号,或者就

  • C#获取硬盘编号的方法

    本文实例讲述了C#获取硬盘编号的方法.分享给大家供大家参考.具体实现方法如下: ManagementClass mc = new ManagementClass("Win32_PhysicalMedia"); //Win32_DiskDrive不包含SerialNumber属性. ManagementObjectCollection moc = mc.GetInstances(); string strID = null ; foreach( ManagementObject mo i

  • C#修改MAC地址类的实例

    1.更新MAC地址 将注册表中的键值添加上MAC地址 2.重新连接网络  试过了3个方法:   ManagementClass最新提供了Disable,Enable方法,但只支持Vista操作系统   Shell.dll的方法,可以实现,但处理起来很烦,另外在重新连接时显示"启动中"提示框,不友好. NetSharingManagerClass 的Disconnect, Connect方法,可以实现,但有一个问题是,会重新更新IP地址,有明显感觉等. 复制代码 代码如下: using

  • linux下修改MAC地址问题解决方法

    在linux中,修改MAC地址 # ifdown eth0 # ifconfig eth0 hw ether 12:34:56:78:90:12 (修改的MAC地址跟原来的地址不同) # ifup eth0 (修改成功) 后,用# ifconfig 查看,MAC地址改变了,但之后输入#service network restart 或ifdowneth0命令时,会出现如下错语信息: Device eth0 has MAC address 12:34:56:78:90:12, instead of

  • 如何修改 mac地址的方法

    各个不同品牌的网卡有专用的刷新程序,需要针对芯片型号下载相应的刷新程序 轻松修改网卡MAC地址   网卡的MAC地址是固化在网卡EPROM中的物理地址,是一块网卡的"身份证",通常为48位.在平常的应用中,有很多方面与MAC地址相关,如有些软件是和MAC地址绑定的,没有允许的MAC地址,软件就无法运行:或者在局域网里,管理人员常常将IP与客户机的MAC地址绑定,以方便管理,万一用户的网卡坏掉了,自行更改网卡后必须向管理人员申请更改绑定的MAC地址,这样就比较麻烦.在这种时候,如果我们能

  • 不用任何软件修改mac地址的图文方法

    其实这样的修改方式很简单:第一步:右键"我的电脑",再点一下"属性" 然后你会看到这个熟悉的窗口 点一下"设备管理器" 在"设备管理器"里面找到网卡 右键网卡,点一下"属性 看到上面的没有,我什么都没有操作的,这些都是系统默认的!好了在修改之前,我们看一下我现在PC的MAC地址(给大家做了教程以后,我还要修改回来的,所以呢,先看一下吧!) 看到没有,我计算机本机的MAC地址是这个 下面我就修改了哦!! 修改好以后,点

  • linux修改mac地址方法分享

    复制代码 代码如下: sudo ifconfig wlan0 down&&sudo ifconfig wlan0 hw ether 12:34:56:78:9a:bc & sudo ifconfig wlan0 up 上面的"wlan0"是自己网卡的名称,我这个显然是无线网卡,具体因设备而定,请使用ifconfig -a来查看和选择:那个MAC地址是我杜撰的,你要改成哪个就写哪个. 需要说明的是,网卡的MAC地址是在硬件中写死的,所以不用担心这种方法会永久改变M

  • java 获取用户的MAC地址多种方法实例详解

    java实现获取用户的MAC地址方法: 方法一:将本机地址与局域网内其他机器区分开来 /** * 根据IP地址获取mac地址 * @param ipAddress 127.0.0.1 * @return * @throws SocketException * @throws UnknownHostException */ public static String getLocalMac(String ipAddress) throws SocketException, UnknownHostEx

  • PHP获取MAC地址的具体实例

    本节分享的php代码,主要功能:获取机器网卡的物理(MAC)地址.代码: 复制代码 代码如下: <?php  /**   * 获取机器网卡的物理(MAC)地址* 目前支持WIN/LINUX系统   **/  class MacAddInfo {          var $return_array = array (); // 返回带有MAC地址的字串数组        var $mac_addr; function MacAddInfo($os_type) {          switch

  • C#获取局域网MAC地址的简单实例

    效果: 说明:获取本局域网的MAC地址(非本机的MAC地址) 代码: 复制代码 代码如下: /// <summary>         /// 获取网卡物理地址         /// </summary>         /// <returns></returns>         public static string getMAC()        {            string madAddr = null;            Man

  • vbs Windows系统改变或修改网卡的MAC地址的脚本与软件

    核心代码 '/*========================================================================= ' * Intro 网上找了一圈,都不怎么好,有一个比较不错的,汉化作者汉化时加了个自己的介绍文件,这个文件比程序本身还大,感觉不爽,于是本人的VBS版MAC修改代码便诞生了,在使用过程中如果出现不能上网的情况得返回一下网卡驱动(有些机器比较特别),如果要返回以前的MAC可以:开始-->控制面板-->网络连接-->点击您的网卡

  • VMware克隆虚拟机后修改UUID、MAC地址、IP和主机名 静态ip设置方法

    1.首先选中需要克隆的虚拟机,右键点击管理-->克隆,注意关闭虚拟机 2.修改MAC地址,一般克隆完成后,虚拟机的网卡MAC地址会自动改变的,如果没有自动改变,可以手动修改. 选中虚拟机,选择编辑虚拟机设置(或者右键设置),选择网络适配器,然后点击右边的高级: 点击生成,就可以重新生成网卡MAC地址 在将生成的MAC地址写入/etc/sysconfig/network-scripts/ifcfg-ens33文件 3.修改UUID,UUID克隆虚拟机后一般是一样的,需要进行修改 输入命令uuidg

随机推荐