Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value out of range exception when setting a string member of INetFwRule

I'm trying to add a firewall rule for TCP Port 1433, with a specific group using the NetFwTypeLib library. But adding the port into the LocalPorts variable as integer converted into a string or just as a simple "1433" string, returns a Value out of range exception. Removing the port and just using all ports works fine.

Here is the code I used:

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

Setting the firewallRule.LocalPorts member causes the exception. Does someone have an idea what's going wrong?

like image 239
Vinz Avatar asked Sep 17 '15 14:09

Vinz


1 Answers

You have to put the Protocol type before the Port, so it is valid.

like image 187
St0rmy Avatar answered Sep 22 '22 13:09

St0rmy