using System;
using Microsoft.Win32;
using System.Diagnostics;
using System.Net.NetworkInformation;
class MacAddressChanger
{
static void Main(string[] args)
{
// 需要管理员权限
if (!IsAdministrator())
{
Console.WriteLine("请以管理员身份运行此程序");
return;
}
string interfaceName = "以太网"; // 改为你的网络连接名称(中文系统常用"以太网"/"WLAN")
string newMacAddress = "001122334455"; // 12位十六进制MAC地址(不要分隔符)
try
{
// 获取网卡ID
string interfaceId = GetInterfaceId(interfaceName);
if (string.IsNullOrEmpty(interfaceId))
{
Console.WriteLine($"找不到网络适配器: {interfaceName}");
return;
}
// 修改注册表
ChangeMacInRegistry(interfaceId, newMacAddress);
Console.WriteLine("MAC地址修改成功!需要重启网卡生效...");
// 重启网卡(可选)
RestartNetworkAdapter(interfaceName);
Console.WriteLine("操作完成!");
}
catch (Exception ex)
{
Console.WriteLine($"错误: {ex.Message}");
}
}
// 检查管理员权限
static bool IsAdministrator()
{
var identity = System.Security.Principal.WindowsIdentity.GetCurrent();
var principal = new System.Security.Principal.WindowsPrincipal(identity);
return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
}
// 获取网络接口ID
static string GetInterfaceId(string interfaceName)
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.Name.Equals(interfaceName))
{
return nic.Id;
}
}
return null;
}
// 修改注册表
static void ChangeMacInRegistry(string interfaceId, string newMacAddress)
{
string registryPath = $@"SYSTEM\CurrentControlSet\Control\Class\{{4d36e972-e325-11ce-bfc1-08002be10318}}";
using (RegistryKey baseKey = Registry.LocalMachine.OpenSubKey(registryPath, true))
{
if (baseKey == null) throw new Exception("注册表路径不存在");
foreach (string subkeyName in baseKey.GetSubKeyNames())
{
using (RegistryKey subKey = baseKey.OpenSubKey(subkeyName, true))
{
if (subKey?.GetValue("NetCfgInstanceId")?.ToString() == interfaceId)
{
subKey.SetValue("NetworkAddress", newMacAddress, RegistryValueKind.String);
return;
}
}
}
}
throw new Exception("找不到对应的网络适配器注册表项");
}
// 重启网卡
static void RestartNetworkAdapter(string interfaceName)
{
ProcessStartInfo psi = new ProcessStartInfo("netsh", $"interface set interface \"{interfaceName}\" disable")
{
WindowStyle = ProcessWindowStyle.Hidden
};
Process.Start(psi)?.WaitForExit();
psi.Arguments = $"interface set interface \"{interfaceName}\" enable";
Process.Start(psi)?.WaitForExit();
}
}