27

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

sundeep
  • 4,048
  • 7
  • 25
  • 22
  • 1
    "allowing for productivity to skyrocket".... who's productivity? Sure, I waste plenty of time trolling the intarwebs, but with no access at all, I'm unable to look up critical references for language, library or frameworks. – SingleNegationElimination Aug 07 '09 at 02:32
  • 1
    We had our connection drop for about an hour today, and I really was in a bind. No access to the customer site for an update, and no access to any reference material. If you're finding you are distracted by easy access to the internet too much, then try breaking down your tasks into smaller subtasks. Basically use the "Getting Things Done" method by David Allen. If you have a list of small incremental steps that will drive the work forward, it really helps with the motivation. – Scott Whitlock Aug 07 '09 at 02:50
  • 5
    The "allowing for productivity to skyrocket" comment was supposed to be a joke guys :) – sundeep Aug 24 '09 at 22:54

5 Answers5

50

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.

Greg
  • 3,731
  • 1
  • 29
  • 25
  • 7
    To add the FirewallAPI.dll, you'll have to browse to c:\windows\system32 – Gyuri Dec 14 '11 at 00:46
  • Some error stating firewallPolicy.Rules as readony... cannot add the rules – KoolKabin Sep 20 '12 at 11:26
  • Windows 10, Visual Studio 2019 C# - Working perfectly! App must be run as Administrator for effect or you get a exception from HRESULT. Thanks man! – WiiLF Oct 19 '21 at 00:06
5

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;
    }
}
newbieguy
  • 658
  • 2
  • 11
  • 29
4

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

Community
  • 1
  • 1
HiredMind
  • 1,827
  • 17
  • 27
  • If you have an active local network connection, it might connect you to the internet. I don't think there is any way of blocking internet access without blocking all network access (after all the internet is just a collection of networks). – Richard Aug 07 '09 at 13:37
  • Actually you can usually find the interface that connects you to the internet by looking at the routing table. The default route (0.0.0.0) almost always points to the interface that connects to the internet (I'd guess 95% of configurations are set up this way) – HiredMind Sep 10 '09 at 18:31
1

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;
        }
    }
}
DWright
  • 9,258
  • 4
  • 36
  • 53
-2
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);
}
Bugs
  • 4,491
  • 9
  • 32
  • 41
Anand Kishore
  • 111
  • 2
  • 9
  • Add this reference dll "FirewallAPI.dll " you will find this in system32. this set of code will block all the outbound connection for your system. – Anand Kishore Jul 12 '17 at 11:29
  • Maybe this answer didn't help OP in achieving what they intended, but, to be honest, I was quickly able to read the firewall status of connections for all profiles (Public / Private / Domain). Unfortunately, I can't upvote this answer for my own benefits. Still, I appreciate the post and the answerer. – Am_I_Helpful Jun 15 '18 at 13:53