C#修改MAC地址类及操作网卡类

2021-04-15 02:25

阅读:669

标签:summary   .net   alt   netstat   支持   address   lan   return   klist   

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}");
            IListstring> 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
    }
}
技术分享图片

操作网卡类:

技术分享图片
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Collections;
 
namespace NetWorkControl
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            NetWorkList();
        }
 
        /// /// 网卡列表
        /// public void NetWorkList()
        {
            string manage = "SELECT * From Win32_NetworkAdapter";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(manage);
            ManagementObjectCollection collection = searcher.Get();
            Liststring> netWorkList = new Liststring>();
 
            foreach (ManagementObject obj in collection)
            {
                netWorkList.Add(obj["Name"].ToString());
                 
            }
           this.cmbNetWork.DataSource = netWorkList;
 
        }
 
        /// /// 禁用网卡
        /// 5
        /// 
网卡名
        /// public bool DisableNetWork(ManagementObject network)
        {
            try
            {
                network.InvokeMethod("Disable", null);
                return true;
            }
            catch
            {
                return false;
            }
        }
 
        /// /// 启用网卡
        /// /// 
网卡名
        /// public bool EnableNetWork(ManagementObject network)
        {
            try
            {
                network.InvokeMethod("Enable", null );
                return true;
            }
            catch
            {
                return false;
            }
             
        }
 
        /// /// 网卡状态
        /// /// 
网卡名
        /// public bool NetWorkState(string netWorkName)
        {
            string netState = "SELECT * From Win32_NetworkAdapter";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState);
            ManagementObjectCollection collection = searcher.Get();
            foreach (ManagementObject manage in collection)
            {
                if (manage["Name"].ToString() == netWorkName )
                {
                    return true;
                }
            }
            return false;
        }
 
        /// /// 得到指定网卡
        /// /// 
网卡名字
        /// public ManagementObject NetWork(string networkname)
        {
            string netState = "SELECT * From Win32_NetworkAdapter";
 
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(netState);
            ManagementObjectCollection collection = searcher.Get();
 
            foreach (ManagementObject manage in collection)
            {
                if (manage["Name"].ToString() == networkname)
                {
                    return manage;
                }
            }
 
             
            return null;
        }
 
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (NetWorkState(this.cmbNetWork.SelectedValue.ToString()))
            {
                if (!EnableNetWork(NetWork(this.cmbNetWork.SelectedValue.ToString())))
                {
                    MessageBox.Show("开启网卡失败!");
                }
                else
                {
                    MessageBox.Show("开启网卡成功!");
                }
            }
            else
            {
                MessageBox.Show("网卡己开启!");
            }
 
            NetWorkList();
        }
 
        private void btnStop_Click(object sender, EventArgs e)
        {
 
            if (NetWorkState(this.cmbNetWork.SelectedValue.ToString()))
            {
                if (!DisableNetWork(NetWork(this.cmbNetWork.SelectedValue.ToString())))
                {
                    MessageBox.Show("禁用网卡失败!");
                }
                else
                {
                    MessageBox.Show("禁用网卡成功!");
                }
            }
            else
            {
                MessageBox.Show("网卡己禁用!");
            }
 
            NetWorkList();
        }
 
    }
}
技术分享图片

 

转载自:http://blog.csdn.net/arden27336/article/details/3523203

C#修改MAC地址类及操作网卡类

标签:summary   .net   alt   netstat   支持   address   lan   return   klist   

原文地址:https://www.cnblogs.com/ksufer/p/8901835.html


评论


亲,登录后才可以留言!