简体   繁体   English

有什么方法可以使用c#在Windows中关闭“互联网”?

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

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. 我正在寻找c#中API的指针,这将允许我通过打开和关闭连接来控制我的Internet连接。

I want to write a little console app that will allow me to turn my access on and off , allowing for productivity to skyrocket :) (as well as learning something in the process) 我想写一个小的控制台应用程序,允许我打开和关闭我的访问权限,允许生产力飞涨:)(以及在过程中学习的东西)

Thanks !! 谢谢 !!

If you're using Windows Vista you can use the built-in firewall to block any internet access. 如果您使用的是Windows Vista,则可以使用内置防火墙阻止任何Internet访问。

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: 如果要再次允许Internet访问,请删除规则:

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. 再一次,请记住,您需要Windows Vista(或更高版本)和管理权限才能使用。

Link to the firewall API documentation. 链接到防火墙API文档。

There are actually a myriad of ways to turn off (Read: break) your internet access, but I think the simplest one would be to turn of the network interface that connects you to the internet. 实际上有很多方法可以关闭(阅读:中断)你的互联网访问,但我认为最简单的方法是关闭连接你到互联网的网络接口。

Here is a link to get you started: Identifying active network interface 这是一个帮助您入门的链接: 识别活动网络接口

This is what I am currently using (my idea, not an api): 这就是我目前使用的(我的想法,而不是api):

System.Diagnostics;    

void InternetConnection(string str)
{
    ProcessStartInfo internet = new ProcessStartInfo()
    {
        FileName = "cmd.exe",
        Arguments = "/C ipconfig /" + str,
        WindowStyle = ProcessWindowStyle.Hidden
    };  
    Process.Start(internet);
}

Disconnect from internet: InternetConnection("release"); 断开互联网连接: InternetConnection("release");
Connect to internet: InternetConnection("renew"); 连接到互联网: InternetConnection("renew");

Disconnecting will just remove the access to internet (it will show a caution icon in the wifi icon). 断开连接只会删除对互联网的访问(它会在wifi图标中显示一个警告图标)。 Connecting might take five seconds or more. 连接可能需要五秒或更长时间。

Out of topic : 超出主题
In any cases you might want to check if you're connected or not (when you use the code above), I better suggest this: 在任何情况下,您可能想要检查您是否已连接(当您使用上述代码时),我建议您:

System.Net.NetworkInformation;

public static bool CheckInternetConnection()
{
   try
   {
       Ping myPing = new Ping();
       String host = "google.com";
       byte[] buffer = new byte[32];
       int timeout = 1000;
       PingOptions pingOptions = new PingOptions();
       PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
            return (reply.Status == IPStatus.Success);
    }
    catch (Exception)
    {
       return false;
    }
}

Here's a sample program that does it using WMI management objects. 这是一个使用WMI管理对象执行此操作的示例程序。

In the example, I'm targeting my wireless adapter by looking for network adapters that have "Wireless" in their name. 在示例中,我通过查找名称中包含“无线”的网络适配器来定位我的无线适配器。 You could figure out some substring that identifies the name of the adapter that you are targeting (you can get the names by doing ipconfig /all at a command line). 您可以找出一些子字符串来标识您要定位的适配器的名称(您可以通过在命令行执行ipconfig /all来获取名称)。 Not passing a substring would cause this to go through all adapters, which is kinda severe. 不传递子字符串会导致它通过所有适配器,这有点严重。 You'll need to add a reference to System.Management to your project. 您需要向项目添加对System.Management的引用。

using System;
using System.Management;

namespace ConsoleAdapterEnabler
{
    public static class NetworkAdapterEnabler
    {
        public static ManagementObjectSearcher GetWMINetworkAdapters(String filterExpression = "")
        {
            String queryString = "SELECT * FROM Win32_NetworkAdapter";
            if (filterExpression.Length > 0)
            {
                queryString += String.Format(" WHERE Name LIKE '%{0}%' ", filterExpression);
            }
            WqlObjectQuery query = new WqlObjectQuery(queryString);
            ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(query);
            return objectSearcher;
        }

        public static void EnableWMINetworkAdapters(String filterExpression = "")
        {
            foreach (ManagementObject adapter in GetWMINetworkAdapters(filterExpression).Get())
            {
                //only enable if not already enabled
                if (((bool)adapter.Properties["NetEnabled"].Value) != true)
                {
                    adapter.InvokeMethod("Enable", null);
                }
            }
        }

        public static void DisableWMINetworkAdapters(String filterExpression = "")
        {
            foreach (ManagementObject adapter in GetWMINetworkAdapters(filterExpression).Get())
            {
                //If enabled, then disable
                if (((bool)adapter.Properties["NetEnabled"].Value)==true)
                {
                    adapter.InvokeMethod("Disable", null);
                }
            }
        }

    }
    class Program
    {
        public static int Main(string[] args)
        {
            NetworkAdapterEnabler.DisableWMINetworkAdapters("Wireless");

            Console.WriteLine("Press any key to continue");
            var key = Console.ReadKey();

            NetworkAdapterEnabler.EnableWMINetworkAdapters("Wireless");

            Console.WriteLine("Press any key to continue");
            key = Console.ReadKey();
            return 0;
        }
    }
}
public static void BlockingOfData()
{
    INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));

    firewallPolicy.set_DefaultOutboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_DOMAIN, NET_FW_ACTION_.NET_FW_ACTION_BLOCK);
    firewallPolicy.set_DefaultOutboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PRIVATE, NET_FW_ACTION_.NET_FW_ACTION_BLOCK);
    firewallPolicy.set_DefaultOutboundAction(NET_FW_PROFILE_TYPE2_.NET_FW_PROFILE2_PUBLIC, NET_FW_ACTION_.NET_FW_ACTION_BLOCK);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM