C#修改MAC地址类的实例
发布时间:2023-09-11 06:51:14
标签:修改,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#实现输入10个数存入到数组中并求max和min及平均数的方法。分享给大家供大家参考,具体如下:using System;u
- Reflections通过扫描classpath,索引元数据,并且允许在运行时查询这些元数据。使用Reflections可以很轻松的获取以下
- 错误示例,同一个类中使用异步方法:package com.xqnode.learning.controller;import com.fas
- HtmlAgilityPack 是一个开源的快速解析Html的C#类库。简单理解,它可以像解析Xml一样,将Html根据XPATH转化为一个
- Android仿通话来电界面,供大家参考,具体内容如下简介:开发中需要模拟来电时的通话界面,仿照来电界面实现来电时播放铃声,界面通过动画模拟
- 1.使用的注意事项本节给大家带来基础UI控件部分的最后一个控件:DrawerLayout,官方给我们提供的一个侧滑菜单控件,和上一节的Vie
- 1.新建一个filter‘包2.新建一个类,实现ZuulFilter,重写里面的方法3.在顶部类添加注解,@Component,让Sprin
- C#在程序中定义和使用自定义事件可以分为以下几个步骤:步骤1:在类中定义事件using System;public class TestCl
- Optional在JAVA中被定义为一个容器类,更确切的说只存一个元素的容器。container object which may or m
- 多文件上传就是改良一个方法把MultipartFile类换成CommonsMultipartFile类,因为上传多个文件用数组方式的话Mul
- 机器跑了一晚上,发现有崩溃现象,由于页面内有动态绘图功能,我怀疑是绘图原因,但是今天上午有人提醒我才想到,是不是间隔调用时DWR产生了内存泄
- 面试题1:说一下抽象类和接口有哪些区别?正经回答:抽象类和接口的主要区别:从设计层面来说,抽象类是对类的抽象,是一种模板设计;接口是行为的抽
- 本文实例为大家分享了Java实现寻找迷宫出路的具体代码,供大家参考,具体内容如下项目名称寻找迷宫出路项目描述给定一个自定义迷宫,0表示能通过
- 本文实例讲述了C#实现发送邮件的三种方法。分享给大家供大家参考。具体方法分析如下:一、问题:最近公司由于一个R&I项目的需要,用户要
- 1.CAS1)CAS概念CAS时Compare And Swap缩写,即比较与交换是用于实现多线程同步的原子指令,它将内存位置的内容与给定值
- Demo环境JDK8Maven3.6.3springboot2.4.3redis_version:6.2.1仓库地址https://gite
- 本文实例讲述了java中response对象用法。分享给大家供大家参考,具体如下:<jsp:forward>动作元素用于运行时在
- 前言上一篇做了一个滑动折叠的Header控件,主要就是练习了一下滑动事件冲突的问题,控件和文章写的都不怎么样。本来想通过这篇文章的控件,整合
- 后端实现1. 数据库设计我们需要设计两个表:用户表和角色表。用户表字段 类型 描述id bigint(20) 用户 IDusername v
- 前言一直很好奇Android Root的原理,恰好最近碰到了一个跟Android默认带Root权限的问题,这里顺便记录一下Android系统