Any way to turn the “internet off” in windows using c#?

前端 未结 5 1331
误落风尘
误落风尘 2020-11-28 05:17

I am looking for pointers towards APIs in c# that will allow me to control my Internet connection by turning the connection on and off.

I want to write a little con

5条回答
  •  我在风中等你
    2020-11-28 05:45

    If you're using Windows Vista you can use the built-in firewall to block any internet access.

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

    Then remove the rule when you want to allow internet access again:

    INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(
        Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));
    firewallPolicy.Rules.Remove("Block Internet");
    

    This is a slight modification of some other code that I’ve used, so I can’t make any guarantees that it’ll work. Once again, keep in mind that you'll need Windows Vista (or later) and administrative privileges for this to work.

    Link to the firewall API documentation.

提交回复
热议问题