创建防火墙规则,以c#编程方式打开每个应用程序的端口

本文关键字:应用程序 方式打 规则 防火墙 编程 创建 | 更新日期: 2023-09-27 18:17:55

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

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

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

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

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

是否有任何方法可以以编程方式打开每个应用程序的单个端口?

创建防火墙规则,以c#编程方式打开每个应用程序的端口

有一个关于阻塞连接的问题,答案是在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);

你也可以直接使用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();
}
相关文章: