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

操作网卡类:

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();
        }

        /// <summary>
        /// 网卡列表
        /// </summary>
        public void NetWorkList()
        {
            string manage = "SELECT * From Win32_NetworkAdapter";
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(manage);
            ManagementObjectCollection collection = searcher.Get();
            List<string> netWorkList = new List<string>();

            foreach (ManagementObject obj in collection)
            {
                netWorkList.Add(obj["Name"].ToString());

            }
           this.cmbNetWork.DataSource = netWorkList;

        }

        /// <summary>
        /// 禁用网卡
        /// </summary>5
        /// <param name="netWorkName">网卡名</param>
        /// <returns></returns>
        public bool DisableNetWork(ManagementObject network)
        {
            try
            {
                network.InvokeMethod("Disable", null);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 启用网卡
        /// </summary>
        /// <param name="netWorkName">网卡名</param>
        /// <returns></returns>
        public bool EnableNetWork(ManagementObject network)
        {
            try
            {
                network.InvokeMethod("Enable", null );
                return true;
            }
            catch
            {
                return false;
            }

        }

        /// <summary>
        /// 网卡状态
        /// </summary>
        /// <param name="netWorkName">网卡名</param>
        /// <returns></returns>
        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;
        }

        /// <summary>
        /// 得到指定网卡
        /// </summary>
        /// <param name="networkname">网卡名字</param>
        /// <returns></returns>
        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

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

时间: 2024-10-29 03:57:18

C#修改MAC地址类及操作网卡类的相关文章

dSploitzANTI渗透教程之修改MAC地址与Wifi监听器

dSploitzANTI渗透教程之修改MAC地址与Wifi监听器 dSploitzANTI基本配置 渗透测试是一种安全性较大的工作.所以,在实施渗透测试之前进行一些简单设置.如修改MAC地址.了解网络等.通过进行简单的配置,不仅可以保护自己的身份被暴漏,而且还可以提高渗透效率.因此,本章将介绍一些基本配置. 修改MAC地址 由于zANTI是一款渗透测试工具,所以在扫描时可能会被一些安全软件拦截,如360.因此,为了不暴漏自己的真实身份,用户可以在渗透之前修改自己的MAC地址.下面将介绍修改MAC

用派克斯出现651 查看&修改mac地址的方法

1.winxp查看mac地址的方法 2.winxp修改mac地址的方法 电脑MAC地址是网卡适配器在出厂时就已经被固定了的,也叫物理地址,每块网卡适配器有全球唯一的MAC地址,一般情况是不需要修改MAC地址的,但有些特殊情况需要更改MAC地址来实现一些特殊的要求,修改之前大家先知道如何查看 第一种方法 1.在开始菜单栏选择"运行" 2.在运行中输入"cmd" 3.我们会看到有一个黑色窗口弹出,在里边输入"ipconfig /all"然后按回车键

vmware克隆centos修改mac地址

故障背景: 克隆完虚拟机后,连不上网,ifconfig查看后,发现网卡eth0没有启动,于是ifconfig eth0 up 启动eth0网卡,结果启动不了,进入/etc/sysconfig/network-scripts/ifcfg-eth0查看后,发现MAC地址和IP地址与原机相同,于是修改IP后service network restart 重启网络服务,发现提示提示 Bringing up interface eth0: Device eth0 does not seem to be p

Linux下永久修改MAC地址和ifconfig命令总结

1. 固定一个MAC地址,特别是在使用多个虚拟机的时候 linux环境下: 用root身份登录,在/etc/rc.d/rc.local里加上这三句 ifconfig eth0 down ifconfig eth0 hw ether 00:0C:18:EF:FF:ED ifconfig eth0 up 这样重新reboot后就不怕MAC复原了. 2. ifconfig命令(转载http://www.cnblogs.com/taobataoma/archive/2007/12/27/1016689.

unbntu修改mac地址

分享下Ubuntu下更改MAC地址的简单方法: 首先把网卡设备给 down 掉,否则会报告系统忙,无法更改. sudo ifconfig eth0 down 然后修改 MAC 地址,这一步较 Windows 中那图形化的修改要简单得多. sudo ifconfig eth0 hw ether 00:AA:BB:CC:DD:EE (你的MAC地址,随便啦,XXOO的,反正是0-9.A-F就行) 改好了在把网卡设备给 up 起来,然后为了保险起见可以再重启一下网络服务,赶紧继续看 F1 . sudo

Windows修改MAC地址

谈起mac地址我想大多数人都比较清楚,一旦我们设置了它就能在局域网防止别人盗用你的ip,不过如果mac地址被别人知道了就得修改一下,很多用户不知道Win7怎么改mac地址?其实这个问题很简单,不知道的朋友可以看看小编整理的Win7改mac地址方法. 方法/步骤: 1.打开开始菜单,选择控制面板. 2.打开控制面板项,选择网络和共享中心. 3.选择更改适配器设置. 4.选择本地要修改mac地址的网卡. 5.右键该网卡,选择属性. 6.从弹出的属性设置框中选择配置. 7.进行配置设置框,选择高级选项

win7H5棋牌源码搭建修改mac地址的三种方法

H5棋牌源码搭建出租出售,都可联系Q1446595067官网: h5.haozibbs.com Win7修改MAC地址方法有以下三种: 方法一:使用Win7MAC地址修改工具 1,只适用于windows7系统的网卡MAC地址修改.XP的可以用,但没做什么测试. 2,部分windows7下的无线网卡地址无法修改,理论上也可以使用本软件修改. 3,修改MAC地址前,请先在开始菜单-运行,输入cmd打开控制台,输入getmac获取原来网卡MAC并记下来,用于以后可以改回来. 4,软件使用方法很简单,只

linux下修改MAC地址的问题解决

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

手动修改MAC地址可以突破IP-MAC绑定吗?

这个世界有矛就有盾,既然有IP-MAC绑定的技术,总归就有人会尝试去突破这个绑定.一般来说,无非是通过"修改IP地址"和"修改MAC地址"两种方式. 1. IP地址的修改很简单,在"本地连接"里面,修改TCP/IP的属性就可以,如图: 2. 大多数人不知道,其实电脑还可以修改"MAC地址".如下图: 3. 所以,要防止客户机通过修改IP地址和mac地址来突破IP-MAC绑定策略,不但要对绑定列表外的IP地址禁止其上网,而且要屏