我正在处理继承的C#应用程序,它以编程方式创建了一些防火墙规则。默认情况下,它禁用特定接口上的所有内容,然后允许访问几个指定的TCP端口,这很好。我无法弄清楚如何修改代码以允许该端口响应ping命令,并且无法在其他搜索中在线找到任何能做到这一点的代码。
有人知道如何使用C#创建防火墙规则以允许端口响应ping命令吗?该应用程序将部署在64位Windows 7嵌入式系统中。
以下是一些现有代码,这些代码创建了打开TCP端口的规则,效果很好:
private void SetupFirewallAllowIncomingRule(int port)
{
try
{
_log.Debug("Creating instance of Windows Firewall policy (HNetCfg.FwPolicy2)...");
INetFwPolicy2 firewallPolicy = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2")) as INetFwPolicy2;
if (null == firewallPolicy)
{
_log.Error("HNetCfg.FwPolicy2 instance could not be created!");
return;
}
string name = "Rule Port " + port.ToString();
foreach (INetFwRule2 rule in firewallPolicy.Rules)
{
if (name.Equals(rule.Name))
{
_log.WarnFormat("Windows Firewall Rule ({0}) already exists. It will not be created again.", rule.Name);
return;
}
}
_log.Debug("Creating new Windows Firewall Rule (HNetCfg.FWRule)...");
INetFwRule firewallRule = Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FWRule")) as INetFwRule;
if (null == firewallRule)
{
_log.Error("HNetCfg.FWRule instance could not be created!");
return;
}
firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;
firewallRule.Direction = NET_FW_RULE_DIRECTION_.NET_FW_RULE_DIR_IN;
firewallRule.Enabled = true;
firewallRule.InterfaceTypes = "All";
firewallRule.Name = name;
firewallRule.Protocol = (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP;
//NOTE: Must do this after setting the Protocol!
firewallRule.LocalPorts = port.ToString();
_log.DebugFormat("Adding Windows Firewall Rule {0}...", firewallRule.Name);
firewallPolicy.Rules.Add(firewallRule);
_log.InfoFormat("Windows Firewall Rule {0} added.", firewallRule.Name);
}
catch (Exception ex)
{
_log.Error("Windows Firewall Rule could not be added for port " + port.ToString() + "!", ex);
}
}