Automating Windows Firewall with

后端 未结 3 701
傲寒
傲寒 2020-12-14 13:24

I have C# Application that uses PORT 777 for asynchronous communication and PORT 3306 for communication with My Sql Server. Problems arise when the ports is blocked by a fir

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 14:28

    I came here via Google looking for a .net method of listing the Windows Firewall open ports. The answers described above did not work. Specifically the firewall.LocalPolicy.CurrentProfile.GloballyOpenPorts always had a count of zero. These answers are old and may well apply to Windows 7. What worked for me on Windows 10 was this code.

    using System;
    using System.Collections;
    using NetFwTypeLib;
    
    namespace FirewallPorts
    {
        class FwPorts
        {
            static void Main(string[] args)
            {
                Type fwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2", true);
                INetFwPolicy2 fwPolicy = (INetFwPolicy2)Activator.CreateInstance(fwPolicy2Type);
                int currentProfs = fwPolicy.CurrentProfileTypes;
                NET_FW_PROFILE_TYPE2_ foo = (NET_FW_PROFILE_TYPE2_)currentProfs;
                if (foo.HasFlag(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE))
                    Console.WriteLine("PrivateNet");
                if (!foo.HasFlag(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC))
                    Console.WriteLine("NOT PUBLIC");
                bool fpsEnabled = fwPolicy.IsRuleGroupCurrentlyEnabled["File and Printer Sharing"];
                bool FwEnabled = fwPolicy.FirewallEnabled[NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC] || fwPolicy.FirewallEnabled[NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE];
                Console.WriteLine($"Windows Firewall enabled is {FwEnabled}");
                INetFwRules rules = fwPolicy.Rules;
                foreach (INetFwRule item in rules)
                {
                    if (item.Enabled && item.Name.Contains("Sharing"))
                    {
                        Console.WriteLine(item.Name);
                        Console.WriteLine($"LocalPorts: {item.LocalPorts}, {(NET_FW_PROFILE_TYPE2_)item.Profiles}");
                        Console.WriteLine(item.Description + "\r\n");
                    }
                }
            }
        }
    }
    

    I did not need to open or close Ports but it can be done by changing rule status, or creating new rules and enabling them. Hope this saves someone else a few hours.

提交回复
热议问题