创建防火墙规则以编程方式在C#中打开每个应用程序端口 [英] Create firewall rule to open port per application programmatically in c#

查看:760
本文介绍了创建防火墙规则以编程方式在C#中打开每个应用程序端口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要打开特定的端口我的申请。

我一直在使用每个应用程序 INetFwAuthorizedApplication 规则对所有端口试过了。

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

或者打开一个端口使用 INetFwOpenPort

所有appllications

  firewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(端口)

有没有办法以编程方式打开每个应用程序编程唯一的单端口?
我可以做手工,通过防火墙设置。


解决方案

有一个关于一个答案阻塞连接与在C#创建防火墙规则说明问题。您应该能够适应这对于任何类型的防火墙规则的我想。

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


  

以下code创建一个防火墙规则,阻止任何传出
  在所有的网络适配器建立连接:

 使用NetFwTypeLib; //位于FirewallAPI.dll
...
INetFwRule firewallRule =(INetFwRule)Activator.CreateInstance(
    Type.GetTypeFromProgID(HNetCfg.FWRule));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK;
firewallRule.Description =用来阻止所有的互联网接入。
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT;
firewallRule.Enabled = TRUE;
firewallRule.InterfaceTypes =所有;
firewallRule.Name =阻止互联网;INetFwPolicy2 firewallPolicy =(INetFwPolicy2)Activator.CreateInstance(
    Type.GetTypeFromProgID(HNetCfg.FwPolicy2));
firewallPolicy.Rules.Add(firewallRule);


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.

解决方案

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.

http://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);

这篇关于创建防火墙规则以编程方式在C#中打开每个应用程序端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆