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

拥有回忆 提交于 2019-12-12 07:36:48

问题


I need to open specific port for my application.

I have tried using INetFwAuthorizedApplication rule per application for all ports.

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

Alternatively open one port for all appllications using 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.


回答1:


There's a question about blocking connections with an answer with instructions for creating firewall rules in C#. You should be able to adapt this for any kind of firewall rule I imagine.

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



回答2:


You could also just use 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();
}


来源:https://stackoverflow.com/questions/8488227/create-firewall-rule-to-open-port-per-application-programmatically-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!