2

我继承了一个 C# 应用程序并正在处理它。它以编程方式创建一些防火墙规则。默认情况下,它会禁用特定接口上的所有内容,然后允许一些指定的 TCP 端口访问,这很好。我不知道如何修改代码以允许该端口响应 ping 命令。但是,在其他搜索中找不到任何在线代码可以做到这一点。

有谁知道如何使用 C# 创建防火墙规则以允许端口响应 ping 命令?该应用程序将部署在 64 位嵌入式 Windows 7 中。

这是一些现有的代码,它创建了一个打开 TCP 端口的规则,可以正常工作:

private void SetupFirewallAllowIncomingRule(int port)
{
    try
    {
        _log.Debug("Creating instance of Windows Firewall policy (HNetCfg.FwPolicy2)...");
        INetFwPolicy2 firewallPolicy = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")) as INetFwPolicy2;

        if (null == firewallPolicy)
        {
            _log.Error("HNetCfg.FwPolicy2 instance could not be created!");
            return;
        }

        string name = "Rule Port " + port.ToString();

        foreach (INetFwRule2 rule in firewallPolicy.Rules)
        {
            if (name.Equals(rule.Name))
            {
                _log.WarnFormat("Windows Firewall Rule ({0}) already exists. It will not be created again.", rule.Name);
                return;
            }
        }

        _log.Debug("Creating new Windows Firewall Rule (HNetCfg.FWRule)...");
        INetFwRule firewallRule = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")) as INetFwRule;
    
        if (null == firewallRule)
        {
            _log.Error("HNetCfg.FWRule instance could not be created!");
            return;
        }

        firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
        firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
        firewallRule.Enabled = true;
        firewallRule.InterfaceTypes = "All";
        firewallRule.Name = name;
        firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;

        //NOTE: Must do this after setting the Protocol!
        firewallRule.LocalPorts = port.ToString();

        _log.DebugFormat("Adding Windows Firewall Rule {0}...", firewallRule.Name);

        firewallPolicy.Rules.Add(firewallRule);

        _log.InfoFormat("Windows Firewall Rule {0} added.", firewallRule.Name);
    }
    catch (Exception ex)
    {
        _log.Error("Windows Firewall Rule could not be added for port " + port.ToString() + "!", ex);
    }
}
4

0 回答 0