gpt4 book ai didi

c# - 使用 C# 在 Windows 10 中设置端口防火墙异常(exception)

转载 作者:行者123 更新时间:2023-11-30 21:43:59 24 4
gpt4 key购买 nike

我正在尝试为 Windows 10 设置防火墙异常(exception)。经过大量搜索后,我将这段代码放在一起:

private const string PROGID_OPEN_PORT = "HNetCfg.FWOpenPort";
private const string CLSID_FIREWALL_MANAGER = "{304CE942-6E39-40D8-943A-B913C40C9CD4}";
private NetFwTypeLib.INetFwMgr GetFirewallManager()
{
Type objectType = Type.GetTypeFromCLSID(
new Guid(CLSID_FIREWALL_MANAGER));
return Activator.CreateInstance(objectType)
as NetFwTypeLib.INetFwMgr;
}

INetFwMgr manager = GetFirewallManager();

Type type = Type.GetTypeFromProgID(PROGID_OPEN_PORT);
INetFwOpenPort port = Activator.CreateInstance(type) as INetFwOpenPort;
port.Name = "MyPortRule";
port.Port = 9600;
port.Scope = NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
port.Protocol = NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
port.IpVersion = NET_FW_IP_VERSION_.NET_FW_IP_VERSION_ANY;

manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port);

这确实将防火墙规则放入具有高级安全性的 Windows 防火墙中,但该规则的配置文件设置为公开。将配置文件设置为公共(public)时,防火墙不会让数据通过该端口。

使用 Windows UI 修改规则,我确定必须将 Profile 设置为“private”或“any”才能使数据通过。为什么不将 port.Scope 设置为 NET_FW_SCOPE_.NET_FW_SCOPE_ALL 将配置文件设置为 Any?如何将防火墙规则中的配置文件设置为私有(private)或任意?

我还尝试将 port.Scope 设置为 NET_FW_SCOPE_.NET_FW_SCOPE_LOCAL_SUBNET。该个人资料仍设置为“公开”。

最佳答案

添加到 GloballyOpenPorts 无效。根据 Stack Overflow 建议的答案,以下代码确实有效。

INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FWRule"));
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
firewallRule.Description = "Enables eATM REST Web Service adapter
traffic.";
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = "MyPort";
firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
firewallRule.LocalPorts = "9600";
INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
firewallPolicy.Rules.Add(firewallRule);

所以...带 firewallPolicy 的 firewallRule 在 INetFwMgr GloballyOpenPorts 不起作用的地方起作用,因为您无法为端口规则设置 Profile 值。

如果 Microsoft 的任何人读到这篇文章,那么获得一些关于如何使用这些功能的文档将会很有帮助。在线文档非常非常差。

关于c# - 使用 C# 在 Windows 10 中设置端口防火墙异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41150964/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com