7

我需要为我的应用程序打开特定的端口。

我已经尝试INetFwAuthorizedApplication对所有端口使用每个应用程序的规则。

fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app)

或者,使用 .为所有应用程序打开一个端口INetFwOpenPort

firewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port)

有没有办法以编程方式以编程方式仅打开每个应用程序的单个端口?我可以通过防火墙设置手动完成。

4

2 回答 2

7

有一个关于阻止连接的问题,答案是在 C# 中创建防火墙规则的说明。您应该能够针对我想象的任何类型的防火墙规则进行调整。

https://stackoverflow.com/a/1243026/12744

以下代码创建一个防火墙规则,阻止所有网络适配器上的任何传出连接:

using NetFwTypeLib; // Located in FirewallAPI.dll
...
INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
    Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Description = "Used to block all internet access.";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = "Block Internet";

INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
    Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(firewallRule);
于 2011-12-14T13:12:30.767 回答
7

您也可以只使用 PowerShell。

using System.Management.Automation;
...
private void OpenPort(int port)
{
    var powershell = PowerShell.Create();
    var psCommand = $"New-NetFirewallRule -DisplayName \"<rule description>\" -Direction Inbound -LocalPort {port} -Protocol TCP -Action Allow";
    powershell.Commands.AddScript(psCommand);
    powershell.Invoke();
}
于 2018-08-19T11:13:51.530 回答