繁体   English   中英

创建防火墙规则以在C#中以编程方式为每个应用程序打开端口

[英]Create firewall rule to open port per application programmatically in 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 \"<rule description>\" -Direction Inbound -LocalPort {port} -Protocol TCP -Action Allow";
    powershell.Commands.AddScript(psCommand);
    powershell.Invoke();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM