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.

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


Solution 1:

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.

Solution 2:

This is what I am currently using (my idea, not an 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");

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.

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

Solution 3:

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

Solution 4:

Here's a sample program that does it using WMI management objects.

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

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