using NetFwTypeLib; using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; namespace SunlightAggregationManager.UserClass { public class NetFwManger { private static string GetName(int port, string protocol) { return "port-" + protocol + "-" + port; } public static void AllowPort(int port, string protocol) { DelPort(port, protocol); //创建一个INetFwRule对象 Type type = Type.GetTypeFromProgID("HNetCfg.FwRule") ?? throw new InvalidOperationException("Failed to retrieve HNetCfg.FwRule type. Ensure the COM component is registered."); INetFwRule? rule = (INetFwRule?)Activator.CreateInstance(type); //设置规则的属性 rule?.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW; //允许连接 rule?.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN; //入站规则 rule?.Enabled = true; //启用规则 rule?.InterfaceTypes = "All"; //适用于所有网络接口 rule?.Name = GetName(port, protocol); //规则名称 if (protocol.ToLower() == "tcp") { rule?.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP; //TCP协议 } else { rule?.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP; //UDP协议 } rule?.LocalPorts = "" + port; //本地端口号 //获取FirewallPolicy对象 Type policyType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2") ?? throw new InvalidOperationException("Failed to retrieve HNetCfg.FwRule type. Ensure the COM component is registered."); INetFwPolicy2? policy = (INetFwPolicy2?)Activator.CreateInstance(policyType); //将规则添加到防火墙策略中 policy?.Rules.Add(rule); } public static void DelPort(int port, string protocol) { //获取FirewallPolicy对象 Type policyType = Type.GetTypeFromProgID("HNetCfg.FwPolicy2") ?? throw new InvalidOperationException("Failed to retrieve HNetCfg.FwRule type. Ensure the COM component is registered."); INetFwPolicy2? policy = (INetFwPolicy2?)Activator.CreateInstance(policyType); //获取现有的规则集合 INetFwRules? rules = policy?.Rules; if (rules != null) { //查找名称的规则并删除它 foreach (INetFwRule rule in rules) { if (rule.Name == GetName(port, protocol)) { rules.Remove(rule.Name); Console.WriteLine(@"Firewall rule deleted successfully."); break; } } } } } }