-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetMasker.cs
More file actions
71 lines (65 loc) · 2.44 KB
/
NetMasker.cs
File metadata and controls
71 lines (65 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using Microsoft.Win32;
using System;
using System.Linq;
using System.Management;
namespace NetMasker
{
public class NetMasker
{
private static RegistryKey networkClassKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}\");
private RegistryKey networkInterfaceKey;
private ManagementObject networkAdapter;
private string deviceId;
private string driverDescription;
private string originalMacAddress;
public NetMasker(string deviceId)
{
this.deviceId = deviceId;
driverDescription = Functions.GetDriverDescriptionById(deviceId);
networkInterfaceKey = networkClassKey.OpenSubKey(deviceId, true);
networkAdapter = new ManagementObjectSearcher($"select * from win32_networkadapter where Name='{driverDescription}'").Get().Cast<ManagementObject>().FirstOrDefault();
originalMacAddress = networkInterfaceKey.GetValue("NetworkAddress")?.ToString() ?? "No establecida";
}
public bool ChangeMacAddress(string newMac = null)
{
if (!DisableNetworkDriver()) return false;
newMac ??= Functions.GenerateValidMacAddress();
networkInterfaceKey.SetValue("NetworkAddress", newMac, RegistryValueKind.String);
bool result = EnableNetworkDriver();
if (result)
{
Console.WriteLine($"MAC original: {originalMacAddress}, MAC nueva: {newMac}");
originalMacAddress = newMac;
}
return result;
}
public bool ResetMacAddress()
{
return ChangeMacAddress(string.Empty);
}
private bool DisableNetworkDriver()
{
try
{
return (uint)networkAdapter.InvokeMethod("Disable", null) == 0;
}
catch (Exception ex)
{
Console.WriteLine($"Error deshabilitando el controlador de red: {ex.Message}");
return false;
}
}
private bool EnableNetworkDriver()
{
try
{
return (uint)networkAdapter.InvokeMethod("Enable", null) == 0;
}
catch (Exception ex)
{
Console.WriteLine($"Error habilitando el controlador de red: {ex.Message}");
return false;
}
}
}
}