You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
71 lines
2.4 KiB
71 lines
2.4 KiB
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using NetFwTypeLib;
|
|
|
|
namespace DyeingComputer.UserClass
|
|
{
|
|
public class NetFwManger
|
|
{
|
|
private static string GetName(int port, string protocol)
|
|
{
|
|
return "800-port-" + protocol + "-" + port;
|
|
}
|
|
|
|
public static void AllowPort(int port, string protocol)
|
|
{
|
|
|
|
DelPort(port, protocol);
|
|
//创建一个INetFwRule对象
|
|
Type type = Type.GetTypeFromProgID("HNetCfg.FwRule");
|
|
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");
|
|
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");
|
|
INetFwPolicy2 policy = (INetFwPolicy2)Activator.CreateInstance(policyType);
|
|
|
|
//获取现有的规则集合
|
|
INetFwRules rules = policy.Rules;
|
|
|
|
//查找名称的规则并删除它
|
|
foreach (INetFwRule rule in rules)
|
|
{
|
|
if (rule.Name == GetName(port, protocol))
|
|
{
|
|
rules.Remove(rule.Name);
|
|
Console.WriteLine(@"Firewall rule deleted successfully.");
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|