如何在Domain network windows防火墙中打开端口

时间:2015-05-30 12:19:18

标签: c# network-programming windows-8.1 windows-firewall

我需要在域网络防火墙中为我的应用程序打开特定端口。

我试过这段代码:

 INetFwOpenPorts ports;
 INetFwOpenPort port = (INetFwOpenPort)Activator.CreateInstance(
Type.GetTypeFromProgID("HNetCfg.FWOpenPort")); ;

 port.Port = 8000; /* port no */
 port.Name = "Application1"; /*name of the application using the port */
 port.Enabled = true; /* enable the port */
 port.Scope = NetFwTypeLib.NET_FW_SCOPE_.NET_FW_SCOPE_ALL;
 port.Protocol = NetFwTypeLib.NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_UDP;//.NET_FW_IP_PROTOCO L_TCP;

 Type NetFwMgrType = Type.GetTypeFromProgID("HNetCfg.FwMgr", false);
 INetFwMgr mgr = (INetFwMgr)Activator.CreateInstance(NetFwMgrType);
 ports = (INetFwOpenPorts)mgr.LocalPolicy.CurrentProfile.GloballyOpenPorts;
 ports.Add(port);

但它不起作用!并且我的数据不会发送,直到Windows防火墙中的域网络开启!

1 个答案:

答案 0 :(得分:0)

在第一步中,添加引用:

  

C:\ Windows \ System32下\ FirewallAPI.dll

下面是具有方法的类:

  
      
  • GloballyOpenPort - 在网络窗口防火墙中打开端口
  •   
  • SetProfilesForRule - 设置配置文件DOMAIN,PRIVATE,PUBLIC for rule
  •   
public class Firewall
{
    private const string CLSID_FIREWALL_MANAGER = "{304CE942-6E39-40D8-943A-B913C40C9CD4}";
    private const string PROGID_AUTHORIZED_APPLICATION = "HNetCfg.FwAuthorizedApplication";
    private const string PROGID_OPEN_PORT = "HNetCfg.FWOpenPort";
    private const string PROGID_POLITCY2 = "HNetCfg.FwPolicy2";

    [Flags]
    public enum PROFILE { DOMAIN = 1, PRIVATE = 2, PUBLIC = 5 };

    /// <summary>
    /// Create instance of the INetFwMgr that provides access to the firewall settings for a computer.
    /// </summary>
    /// <returns></returns>
    private static INetFwMgr GetFirewallManager()
    {
        Type objectType = Type.GetTypeFromCLSID(new Guid(CLSID_FIREWALL_MANAGER));

        return Activator.CreateInstance(objectType) as NetFwTypeLib.INetFwMgr;
    }


    /// <summary>
    /// Enable firewall
    /// </summary>
    public static void Enable()
    {
        INetFwMgr manager = Firewall.GetFirewallManager();

        bool isFirewallEnabled = manager.LocalPolicy.CurrentProfile.FirewallEnabled;

        if (isFirewallEnabled == false)
            manager.LocalPolicy.CurrentProfile.FirewallEnabled = true;
    }


    /// <summary>
    /// Authorize application
    /// </summary>
    /// <param name="title"></param>
    /// <param name="applicationPath"></param>
    /// <param name="scope"></param>
    /// <param name="ipVersion"></param>
    /// <returns></returns>
    public static bool AuthorizeApplication(string title, string applicationPath, NET_FW_SCOPE_ scope, NET_FW_IP_VERSION_ ipVersion)
    {
        // Create the type from prog id
        Type type = Type.GetTypeFromProgID(PROGID_AUTHORIZED_APPLICATION);

        // Create instance that provides access to the properties of an application that has been authorized have openings in the firewall.
        INetFwAuthorizedApplication auth = Activator.CreateInstance(type) as INetFwAuthorizedApplication;
        auth.Name = title;
        auth.ProcessImageFileName = applicationPath;
        auth.Scope = scope;
        auth.IpVersion = ipVersion;
        auth.Enabled = true;


        INetFwMgr manager = GetFirewallManager();
        try
        {
            manager.LocalPolicy.CurrentProfile.AuthorizedApplications.Add(auth);
        }
        catch (Exception ex)
        {
            return false;
        }
        return true;
    }

    /// <summary>
    /// Open port in network windows firewall
    /// </summary>
    /// <param name="name"></param>
    /// <param name="portNo"></param>
    /// <param name="scope"></param>
    /// <param name="protocol"></param>
    /// <param name="ipVersion"></param>
    /// <returns></returns>
    public static bool GloballyOpenPort(string name, int portNo,
                                        NET_FW_SCOPE_ scope, NET_FW_IP_PROTOCOL_ protocol, NET_FW_IP_VERSION_ ipVersion)
    {
        INetFwMgr manager = GetFirewallManager();
        try
        {
            // Check if port does not exists.
            bool exists = false;
            foreach (INetFwOpenPort openPort in manager.LocalPolicy.CurrentProfile.GloballyOpenPorts)
            {
                if (openPort.Name == name && openPort.Port == portNo)
                {
                    exists = true;
                    break;
                }
            }

            if (!exists)
            {
                // Create the type from prog id
                Type type = Type.GetTypeFromProgID(PROGID_OPEN_PORT);
                // Create instance that provides access to the properties of a port that has been opened in the firewall.
                INetFwOpenPort port = Activator.CreateInstance(type) as INetFwOpenPort;

                // Set properties for port
                port.Name = name;
                port.Port = portNo;
                port.Scope = scope;
                port.Protocol = protocol;
                port.IpVersion = ipVersion;

                // Add open port to windows firewall
                manager.LocalPolicy.CurrentProfile.GloballyOpenPorts.Add(port);
            }
        }
        catch (Exception ex)
        {
            return false;
        }
        return true;
    }

    /// <summary>
    /// Set profiles for rule 
    /// </summary>
    /// <param name="name">Name of rule</param>
    /// <param name="profiles">bitmask value: 3 - public; 2 - private; 1 - domain</param>
    /// <returns></returns>
    public static bool SetProfilesForRule(string name, int profiles)
    {
        try
        {
            // Create the type from prog id
            Type typePolicy2 = Type.GetTypeFromProgID(PROGID_POLITCY2);
            // Create instance that allows an application or service to access the firewall policy.
            INetFwPolicy2 policy2 = Activator.CreateInstance(typePolicy2) as INetFwPolicy2;

            // Set profiles for rule                    
            policy2.Rules.Item(name).Profiles = profiles;
        }
        catch (Exception ex)
        {
            return false;
        }
        return true;
    }
}

设置规则配置文件的调用方法示例:

方法中的第一个参数是规则名称

第二个参数是int的配置文件类型,我们可以从枚举类型PROFILE

设置为位掩码
  

int profile =(int)(PROFILE.DOMAIN | PROFILE.PRIVATE |   PROFILE.PUBLIC);   SetProfilesForRule(&#34; RuleName&#34;,profile);