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 = "以太網(wǎng)"; // 改為你的網(wǎng)絡連接名稱(中文系統(tǒng)常用"以太網(wǎng)"/"WLAN")
string newMacAddress = "001122334455"; // 12位十六進制MAC地址(不要分隔符)
try
{
// 獲取網(wǎng)卡ID
string interfaceId = GetInterfaceId(interfaceName);
if (string.IsNullOrEmpty(interfaceId))
{
Console.WriteLine($"找不到網(wǎng)絡適配器: {interfaceName}");
return;
}
// 修改注冊表
ChangeMacInRegistry(interfaceId, newMacAddress);
Console.WriteLine("MAC地址修改成功!需要重啟網(wǎng)卡生效...");
// 重啟網(wǎng)卡(可選)
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);
}
// 獲取網(wǎng)絡接口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("找不到對應的網(wǎng)絡適配器注冊表項");
}
// 重啟網(wǎng)卡
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();
}
}