简体   繁体   English

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

[英]Create firewall rule to open port per application programmatically in c#

I need to open specific port for my application. 我需要为我的应用程序打开特定的端口。

I have tried using INetFwAuthorizedApplication rule per application for all ports. 我尝试对所有端口的每个应用程序使用INetFwAuthorizedApplication规则。

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

Alternatively open one port for all appllications using INetFwOpenPort . 或者,使用INetFwOpenPort为所有应用程序打开一个端口。

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

Is there any way to programmatically open only single port per application programmatically? 是否可以通过编程方式以编程方式为每个应用程序仅打开单个端口? I can do it manually through firewall settings. 我可以通过防火墙设置手动进行操作。

There's a question about blocking connections with an answer with instructions for creating firewall rules in C#. 存在一个问题,该问题的答案是使用C#创建防火墙规则的说明来阻止连接。 You should be able to adapt this for any kind of firewall rule I imagine. 您应该能够适应我想象的任何种类的防火墙规则。

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

The following code creates a firewall rule that blocks any outgoing connections on all of your network adapters: 以下代码创建一个防火墙规则,该规则将阻止所有网络适配器上的所有传出连接:

 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); 

You could also just use PowerShell. 您也可以只使用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