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?
You have to put the Protocol type before the Port, so it is valid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With