我希望能够在特定网络接口上禁用给定的网络过滤器/服务(这就是它们的名字吗?)。例如,根据下面的屏幕截图,我希望能够以编程方式禁用和启用“Npcap 数据包驱动程序 (NPCAP)”。我相信 .NET API 不允许直接操作这些东西,但任何其他解决方案(P/Invoke、COM、CLI 命令等)也很好。我尝试过使用
netsh
命令,但无法确定如何做到这一点。另外,COM 互操作似乎是一个很好的解决方案,但我无法让它工作。
以下是我的 COM 冒险的片段(它使用了这篇 CodeProject 文章中的一些修改后的代码):
INetCfgComponent? devComponent = this.FindComponent(netCfg, deviceName); // INetCfgGuid.IID_DevClassNet
if (devComponent != null)
{
INetCfgComponentBindings devComponentBindings = devComponent.QueryInterface<INetCfgComponentBindings>();
foreach (string serv in servicesToDisable) // for instance, the NPCAP one
{
INetCfgComponent? serviceComponent = this.FindServiceComponent(netCfg, serv); // INetCfgGuid.IID_DevClassNetService
if (serviceComponent != null)
{
INetCfgComponentBindings serviceComponentBindings = serviceComponent.QueryInterface<INetCfgComponentBindings>();
if (serviceComponentBindings.IsBoundTo(devAComponent) == 0) // 0 means bound
{
serviceComponentBindings.UnbindFrom(devAComponent); // error 0x8004A024, even when run as administrator
netCfg.Apply();
}
}
}
}
如代码中所述,即使应用程序以管理员身份运行,我也会遇到错误,并显示消息
0x8004A024
。
您可以使用以下 PowerShell 命令以编程方式实现此目的。您需要使用管理员权限来执行它们。
禁用:
禁用-NetAdapterBinding -名称“适用于 VMnet8 的 VMware 虚拟以太网适配器”| Where-Object {$_.DisplayName -eq "Npcap 数据包驱动程序 (NPCAP)"}
启用:
Enable-NetAdapterBinding -名称“适用于 VMnet8 的 VMware 虚拟以太网适配器”| Where-Object {$_.DisplayName -eq "Npcap 数据包驱动程序 (NPCAP)"}