This commit is contained in:
sc committed 2024-10-22 23:30:20 +08:00
commit b1a86fcad3
3 files changed
+85 -1

No files matched your search

+2 -1
View File
@@ -59,7 +59,8 @@ namespace DyeingComputer.UserClass
}
public static async Task Main()
{
{
NetFwManger.AllowPort(7790,"TCP");//开放7790端口
TcpService service = new TcpService();
service.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接
service.Connected = (client, e) => { return EasyTask.CompletedTask; };//有客户端成功连接
+71
View File
@@ -0,0 +1,71 @@
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;
}
}
}
}
}