设置INetFwRule的

时间:2015-09-17 14:16:18

标签: c# exception firewall

我正在尝试为TCP端口1433添加防火墙规则,使用NetFwTypeLib库的特定组。 但是将端口添加到LocalPorts变量中作为整数转换为字符串或仅作为简单的“1433”字符串,返回值超出范围异常。 删除端口并只使用所有端口工作正常。

以下是我使用的代码:

bool CreateRule(string sName, string sPort, NET_FW_IP_PROTOCOL_ ProtocolType, string sIpAdress, string sGroup = "")
{
    try
    {
        INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule"));

        firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
        firewallRule.Description = "Used to allow Server access.";
        firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
        firewallRule.Enabled = true;
        firewallRule.Name = sName;
        firewallRule.Grouping = sGroup;
        firewallRule.LocalPorts = sPort; // "1433" causes out of range exception
        firewallRule.RemoteAddresses = sIpAdress;
        firewallRule.Protocol = (int)ProtocolType;

        INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
            Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
        firewallPolicy.Rules.Add(firewallRule);

        return true;
    }
    catch
    {
        return false;
    }
}

设置firewallRule.LocalPorts成员会导致异常。 有人知道出了什么问题吗?

1 个答案:

答案 0 :(得分:9)

您必须将协议类型放在端口之前,因此它是有效的。