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

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

问题描述

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

I need to open specific port for my application.

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

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

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

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

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.

推荐答案

有一个关于阻止连接的问题,答案包含在 C# 中创建防火墙规则的说明.您应该能够针对我想象的任何类型的防火墙规则进行调整.

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

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

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