How to add port range?
Hello,
I want to add a port range to a rule but it allows me o add just as short/int; I need to add a port range like "5000-7000" as a string. I can't add 2000 different rules for it.
How can I handle this?
Thank you.
I don't think you can. we are limited by the constraints of the windows firewall here. but I will take a look.
Windows firewall (and its FirewallAPI.dll) allows me to add "5000-7000" as string. All ports will be allowed from 5000 to 7000. But I'd like to use your library, I've already prepared my software with this, I don't want to change it.
Thanks.
I'd like to add my vote for this. In the Windows Firewall console our setting is "21, 990, 5000-5500" but this library just shows "21, 990, 5000, 5001, 5002, ..."
If the API is limited to only individual ports, it would be nice if the library could group them into a range.
So in my solution I just added an extension method to IFirewallRule based on this answer: https://codereview.stackexchange.com/a/219223/274517
I now have
rule.AsRangeString()
which outputs something like this: 5004-5005, 7777-7781, 50004-50013
Which is very much like Windows Firewall shows it
I actually copied both Ranges and Str from that answer and renamed Str to RangeStr and added the extension method like so:
public static string AsRangeString(this IFirewallRule rule) => RangeStr(Ranges(rule.LocalPorts.Select(x => Convert.ToInt32(x)).ToList()));
I could have modified the original answer code to use ushort instead of int and then I would have only needed to convert the ushort[] to a List<ushort> but a List<int> is more usable and I wouldn't have to have multiple versions of it.
There's a class in this repo called PortHelper with a method for converting port strings (including those with ranges) into an array of ports. However, the class is internal so you can't use it directly. Ideally, there would be a public method that allows setting ports for a rule using a string value, which uses PortHelper.StringToPorts. There's a similar class mapping IpAddress string that would also be useful to have for public consumption.
Maybe it will help to somebody, but now you can do it like that:
FirewallWASRule rule_w_ports = new FirewallWASRuleWin8(myRule.FWRule.Name, myRule.FWRule.ApplicationName, fwAction, fwDirection, FirewallProfiles.Domain | FirewallProfiles.Private | FirewallProfiles.Public)
{
Protocol = FirewallProtocol.TCP,
RemotePorts = myRule.FWRule.RemotePorts, // ushort[] RemotePorts
Description = myRule.FWRule.Description,
Grouping = myRule.FWRule.Grouping
};
FirewallWAS.Instance.Rules.Add(rule_w_ports);