C#-使用INetFwPolicy2添加的Windows防火墙规则无效

时间:2018-08-20 13:11:58

标签: c# windows windows-firewall

我正在使用C#中的以下代码编写在Windows上运行的服务器程序。

Type tNetFwPolicy2 = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");
INetFwPolicy2 fwPolicy2 = (INetFwPolicy2)Activator.CreateInstance(tNetFwPolicy2);
foreach (INetFwRule2 rule in fwPolicy2.Rules)
{
    if (rule.Name == ruleName)
    {
        if (!rule.Enabled)
        {
            rule.Enabled = true;
        }
        return;
    }
}
INetFwRule2 inboundRule = (INetFwRule2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));
inboundRule.Enabled = true;
inboundRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
inboundRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
inboundRule.LocalPorts = "8080";
inboundRule.Name = ruleName;               // ruleName is the name of the assembly
inboundRule.ApplicationName = progName;    // progName is the full path to the executable
fwPolicy2.Rules.Add(inboundRule);

这段代码能够向Windows 10添加防火墙规则,该规则显示在Windows 10防火墙和高级安全性对话框中。但是,启用此规则后,我的应用程序仍然无法侦听来自本地网络中其他设备的请求。仅当该规则是未指定允许程序的端口规则时,它才有效。我应该如何配置它,使规则仅允许我的应用程序侦听网络请求?

0 个答案:

没有答案