Mar*_*rek 5 c# api port firewall windows-firewall
我需要为我的应用程序打开特定端口.
我已尝试INetFwAuthorizedApplication
为所有端口使用每个应用程序的规则.
fwMgr.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(app)
Run Code Online (Sandbox Code Playgroud)
或者,为所有应用程序打开一个端口INetFwOpenPort
.
firewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port)
Run Code Online (Sandbox Code Playgroud)
有没有办法以编程方式以编程方式为每个应用程序打开单个端口?我可以通过防火墙设置手动完成.
您也可以只使用 PowerShell。
using System.Management.Automation;
...
private void OpenPort(int port)
{
var powershell = PowerShell.Create();
var psCommand = $"New-NetFirewallRule -DisplayName \"<rule description>\" -Direction Inbound -LocalPort {port} -Protocol TCP -Action Allow";
powershell.Commands.AddScript(psCommand);
powershell.Invoke();
}
Run Code Online (Sandbox Code Playgroud)
关于使用C#中创建防火墙规则的说明来回答阻塞连接的问题.你应该能够适应我想象的任何防火墙规则.
以下代码创建一个防火墙规则,阻止所有网络适配器上的任何传出连接:
Run Code Online (Sandbox Code Playgroud)using NetFwTypeLib; // Located in FirewallAPI.dll ... INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FWRule")); firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_BLOCK; firewallRule.Description = "Used to block all internet access."; firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_OUT; firewallRule.Enabled = true; firewallRule.InterfaceTypes = "All"; firewallRule.Name = "Block Internet"; INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance( Type.GetTypeFromProgID("HNetCfg.FwPolicy2")); firewallPolicy.Rules.Add(firewallRule);
归档时间: |
|
查看次数: |
11886 次 |
最近记录: |