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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1242566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:06:58  来源:igfitidea点击:

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

c#

提问by sundeep

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 !!

谢谢 !!

采纳答案by Greg

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

如果您使用的是 Windows Vista,您可以使用内置防火墙来阻止任何互联网访问。

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.

这是对我使用过的其他一些代码的轻微修改,所以我不能保证它会工作。再次记住,您需要 Windows Vista(或更高版本)和管理权限才能使其工作。

Link to the firewall APIdocumentation.

链接到防火墙 API文档。

回答by HiredMind

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

这是一个帮助您入门的链接: 识别活动网络接口

回答by newbieguy

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");
Connect to internet:InternetConnection("renew");

断开互联网连接:InternetConnection("release");
连接互联网:InternetConnection("renew");

Disconnecting will just remove the access to internet (it will show a caution icon in the wifi icon). Connecting might take five seconds or more.

断开连接只会删除对互联网的访问(它会在 wifi 图标中显示一个警告图标)。连接可能需要五秒钟或更长时间。

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

回答by DWright

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 /allat a command line). 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.

在该示例中,我通过查找名称中包含“Wireless”的网络适配器来定位我的无线适配器。您可以找出一些标识您所针对的适配器名称的子字符串(您可以通过ipconfig /all在命令行中执行来获取名称)。不传递子字符串会导致它通过所有适配器,这有点严重。您需要将 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;
        }
    }
}

回答by Anand Kishore

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