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

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

我已尝试为每个端口使用每个应用程序的INetFwAuthorizedApplication规则。

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

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

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

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

关于使用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 \"\" -Direction Inbound -LocalPort {port} -Protocol TCP -Action Allow"; powershell.Commands.AddScript(psCommand); powershell.Invoke(); }