Create firewall rule to open port per application programmatically in c#

前端 未结 2 955
耶瑟儿~
耶瑟儿~ 2021-02-09 19:56

I need to open specific port for my application.

I have tried using INetFwAuthorizedApplication rule per application for all ports.

fwMgr.Lo         


        
2条回答
  •  暖寄归人
    2021-02-09 20:28

    There's a question about blocking connections with an answer with instructions for creating firewall rules in C#. You should be able to adapt this for any kind of firewall rule I imagine.

    https://stackoverflow.com/a/1243026/12744

    The following code creates a firewall rule that blocks any outgoing connections on all of your network adapters:

    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);
    

提交回复
热议问题