Click here to Skip to main content
Click here to Skip to main content

SwitchNetConfig - Laptop users, quickly switch network and proxy configuration in different places

By , 6 May 2004
 

Introduction

This is a tiny utility which stores multiple network and proxy configuration as profiles. You can apply a profile to set specific network setting and proxy from simple shortcuts.

Background

If you have a laptop, when you go to different places, you have to change Network configuration and browser proxy. I have to go to 4 different places everyday with my laptop; my university, my offices and my home. Everywhere I have to change my IP setting and IE Proxy. I could write a WMI Script to do all of them. Unfortunately, for some reason WMI is not working from VB Script in my laptop but somehow it is working from .NET. So, I have made a handy utility which I can use to store configuration profiles for different places and apply them very quickly just by pressing one key and a ENTER at system startup. This program automatically sets IP, Subnet, Gateway and DNS for my LAN card and also changes the IE Proxy setting.

Using the code

You can setup in 3 easy steps.

  • 1. Click New and enter a profile name.
  • 2. Set IP configuration
  • 3. Set IE Proxy configuration

It’s even easier to use:

  • 1. Press the first letter of your profile. For example, “h” for Home.
  • 2. Press ENTER and wait as it applies the profile.
  • 3. Press ESC to quit.

Points of Interest

It’s a very simple Winforms application written in C#. The key technologies are:

  • 1. WMI
  • 2. IE Registry tweaking
  • 3. XML Serialization

WMI

Windows Management Intrumentation (WMI) helps you work with Network configuration. For example, the following code retrieves Network Setting for a given Network Card.

/// <summary>
/// Returns the network card configuration of the specified NIC
/// </summary>
/// <PARAM name="nicName">Name of the NIC</PARAM>
/// <PARAM name="ipAdresses">Array of IP</PARAM>
/// <PARAM name="subnets">Array of subnet masks</PARAM>
/// <PARAM name="gateways">Array of gateways</PARAM>
/// <PARAM name="dnses">Array of DNS IP</PARAM>
public static void GetIP( string nicName, out string [] ipAdresses, 
  out string [] subnets, out string [] gateways, out string [] dnses )
{
  ipAdresses = null;
  subnets = null;
  gateways = null;
  dnses = null;

  ManagementClass mc = new ManagementClass(
    "Win32_NetworkAdapterConfiguration");
  ManagementObjectCollection moc = mc.GetInstances();

  foreach(ManagementObject mo in moc)
  {
    // Make sure this is a IP enabled device. 
    // Not something like memory card or VM Ware
    if( mo["ipEnabled"] as bool )
    {
      if( mo["Caption"].Equals( nicName ) )
      {
        ipAdresses = (string[]) mo["IPAddress"];
        subnets = (string[]) mo["IPSubnet"];
        gateways = (string[]) mo["DefaultIPGateway"];
        dnses = (string[]) mo["DNSServerSearchOrder"];

        break;
      }
    }
  }
}

“Win32_NetworkAdapterConfiguration” gives you the collection of network adapters installed. Be careful, all the entries in this list may not be your LAN card.

Similarly you can set Network configuration just by a couple of lines.

/// <summary>
/// Set IP for the specified network card name
/// </summary>
/// <PARAM name="nicName">Caption of the network card</PARAM>
/// <PARAM name="IpAddresses">Comma delimited string 
///           containing one or more IP</PARAM>
/// <PARAM name="SubnetMask">Subnet mask</PARAM>
/// <PARAM name="Gateway">Gateway IP</PARAM>
/// <PARAM name="DnsSearchOrder">Comma delimited DNS IP</PARAM>
public static void SetIP( string nicName, string IpAddresses, 
  string SubnetMask, string Gateway, string DnsSearchOrder)
{
  ManagementClass mc = new ManagementClass(
    "Win32_NetworkAdapterConfiguration");
  ManagementObjectCollection moc = mc.GetInstances();

  foreach(ManagementObject mo in moc)
  {
    // Make sure this is a IP enabled device. 
    // Not something like memory card or VM Ware
    if( mo["IPEnabled"] as bool )
    {
      if( mo["Caption"].Equals( nicName ) )
      {

        ManagementBaseObject newIP = 
          mo.GetMethodParameters( "EnableStatic" );
        ManagementBaseObject newGate = 
          mo.GetMethodParameters( "SetGateways" );
        ManagementBaseObject newDNS = 
          mo.GetMethodParameters( "SetDNSServerSearchOrder" );
            
        newGate[ "DefaultIPGateway" ] = new string[] { Gateway };
        newGate[ "GatewayCostMetric" ] = new int[] { 1 };

        newIP[ "IPAddress" ] = IpAddresses.Split( ',' );
        newIP[ "SubnetMask" ] = new string[] { SubnetMask };

        newDNS[ "DNSServerSearchOrder" ] = DnsSearchOrder.Split(',');

        ManagementBaseObject setIP = mo.InvokeMethod( 
          "EnableStatic", newIP, null);
        ManagementBaseObject setGateways = mo.InvokeMethod( 
          "SetGateways", newGate, null);
        ManagementBaseObject setDNS = mo.InvokeMethod( 
          "SetDNSServerSearchOrder", newDNS, null);

        break;
      }
    }
  }
}

Internet Explorer Proxy

Changing Internet Explorer Proxy setting is a tricky job. There are 3 registry keys that you need to handle:

CURRENT_USER\ Software\Microsoft\Windows\CurrentVersion\Internet Settings

  • ProxyServer – string – Name of proxy server
  • ProxyEnable – integer – 1 for enabled, 0 for disabled
  • ProxyOverride – string – a list of hosts that you need to directly access without proxy

XML Serialization

XML Serialization makes it very easy to persist object graph in human readable form. For example, this is the XML that the program generates:

<?xml version="1.0"?>
<ConfigWrapper xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Profiles>
    <anyType xsi:type="Profile">
      <Name>Home</Name>
      <NICProfiles>
        <anyType xsi:type="NICProfile">
          <Name>[00000001] Intel(R) PRO/100 
             VE Network Connection</Name>
          <IP>192.168.2.43</IP>
          <Subnet>255.255.255.0</Subnet>
          <Gateway>192.168.2.1</Gateway>
          <DNS>202.141.190.2,202.141.190.3</DNS>
        </anyType>
      </NICProfiles>
      <IEProfile>
        <UseProxy>true</UseProxy>
        <ProxyName>192.168.2.1:3128</ProxyName>
        <BypassLocal>true</BypassLocal>
        <BypassAddresses />
      </IEProfile>
    </anyType>

It makes it very easy to modify the file manually. You can save an entire object graph just by writing 3 lines of code:

// Use XML Serializer to serialize the content of the specified array list
XmlSerializer serializer = new XmlSerializer( typeof( ConfigWrapper ) );
// open the profile file
StreamWriter writer = new StreamWriter( PROFILE_FILE_NAME, false );        
// Serialize the array list to the file
serializer.Serialize( writer.BaseStream, wrapper );

History

  • Ver 1.0 - Store multiple profiles, multiple NIC setting, IE Proxy
  • (Planning) Ver 2.0 - Execute batch file before and after profile setting

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Omar Al Zabir
Architect BT, UK (ex British Telecom)
United Kingdom United Kingdom
Member

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralAmazing!memberArciel31 Mar '13 - 16:38 
Thanks Omar, It's work great on my laptop!
Questionhow can I make it workable under limited user accountmemberEric Chan1 Jan '13 - 1:08 
I find that this program won't work under limited user account due to privilege problem.
 
Do you have ideas about how to make workable under limited user account.
AnswerRe: how can I make it workable under limited user accountmemberOmar Al Zabir1 Jan '13 - 1:21 
No, Windows does not allow IP settings to be changed from limited user account.
(regards) => "Omar AL Zabir"
+ "C#, ASP.NET MVP"
+ "http://omaralzabir.com";

GeneralRe: how can I make it workable under limited user accountmemberEric Chan1 Jan '13 - 1:27 
can I implement this by
1.building & installing the service [runs under the LocalSystem account]
2.creating a small client that can be run in limited user mode that would command the service to change the network setting.
 
However, I still do not have any idea about how to command the service to change the network setting according to the input from the user [ in a winForm Program]
BugMy vote of 5... but not working in Windows 8memberAlex Galisteo23 Dec '12 - 22:50 
I've tried in Windows 7 and Vista and works perfect. But in windows 8 WMI libraries doesn't seem to work...
GeneralMy vote of 5memberosueque15 Dec '12 - 2:16 
Good Job Omar!
QuestionUnable to change the IPmemberdevil13007811 Nov '12 - 18:36 
I had try to activate the IP and the gateway IP but it does not change after i press activate.
GeneralMy vote of 4memberrajeshhee26 Aug '12 - 18:42 
good
Questionhelp plzmemberAmirAmirA6 Jun '12 - 20:57 
great work! can u please make something tht could change ur ip and proxy settings to something random but working every minute ?
QuestionNice try, but...memberSchmal1 Feb '12 - 17:56 
... (there is always a 'but'):
- Setting IP params always needs admin rights (XP and newer). Switching off UAC or even running your whole session as an admin is not an option. Think of bigger companies: Do you really want to grant local admin rights to all these users?
- Every IP address must respect its corresponding subnet mask, which will be different, depending the size of the subnet. You happen to be lucky as long as you're working on 24 bit subnets only, but as soon as it's no longer "255.255.255.0" everywhere you will need to pair every IP address with its own subnet mask.
 
Thanks for sharing your programming experience but nowadays such a tool shouldn't be needed anymore. A properly configured DHCP server should be setting your NIC when connecting to a network, and IE settings should be propagated automatically as shown for example on [Internet Explorer Automatic Configuration].
 
No offence!
Questionmy vote is 4memberayongwust1 Nov '11 - 0:28 
I'd like to create a similar one before I met yours.
 
It's basically good, except there are some corruption occurred sometimes.
 
thanks, anyway.
QuestionProblem with the proxymemberpatuco30 Sep '11 - 1:08 
Hi , i was trying teh program and trying to add the exceptions for the proxy config but i donot know how to do it because in
BypassProxyForLocal
no parameters are send. Any idea?
Thanks
GeneralMy vote of 5memberBasarat Ali Syed28 Feb '11 - 19:37 
Awesome thanks.
GeneralCommand LinememberTeerachaiJ6 Feb '11 - 19:43 
[MainClass.cs]
Line11 -> public static void Main(string[] args)
 
[MainForm.cs]
Line57 -> string[] g_args;
Line59 -> public MainForm(string[] args)
Line65 -> g_args = args;
Line826 ->
try
{
if (g_args is string[]) //this throw if not has cmdLine
{
cboProfiles.SelectedItem = g_args[0];
applyProfile();
this.Close();
Application.Exit();
}
}
catch
{
}
GeneralThank'smemberRodolfo Centeno Sicche14 Jan '11 - 6:59 
Served me well
Very good article
GeneralWorked well with Win 7 prof.membermaqh19 Mar '10 - 7:15 
Thanks a Lot
 
It worked fine with Win 7 Prof.
 
Best Regards
 
Maqh
GeneralTested with several proxy IP servers and works great!memberproxydev18 Mar '10 - 12:35 
I'm using your application with the proxy ip and port that I downloaded from http://proxy-ip-list.com/ and it works great!
 
Thanks!
GeneralLoad/Save methodmemberanen30 Jan '10 - 18:47 
Hello
I am just wandering , why not use the program as a data base for profiles where you can choose from a list box , all the predefined profiles.
Quick help ??
GeneralRe: Load/Save methodmemberbrk12330 Jun '10 - 2:06 
Great work... i customized and works well.
One question, why not populate the network card from the xml file? everytime query to the WMI takes time depending upon the system speed... i hope file operation would be more faster.
 
during new profile creation alone, the WMI can be queried... just an input..
 
thanks,
brk
GeneralVery nice!memberquicoli1 Jul '09 - 1:48 
Hi!
 
May i use your source to build a version using WPF for UI and make it Vista friendly?
 
thanks!
GeneralRe: Very nice!mvpOmar Al Zabir1 Jul '09 - 6:03 
Sure! You can also share the WPF version and I will put that up here in this article.
 
Regards,
Omar AL Zabir
Visual C# MVP

GeneralThanks!memberlegolasgreenleaf3 Apr '09 - 1:51 
Hi,
 
I was searching for a good tool like yours but they all had some issues.
So now I was searching for how to implement something myself in C-Sharp, when Google pointed me at this project.
With the sources provided I could change it to fit my personal needs.
 
Great, thanks!!
Marcel
GeneralWell Buillt UtilitymemberKannan.P12 Jan '09 - 23:37 
Hats off to Omar.
This tool work well even without single change.
Thanks Omar.
 
kannabiran

GeneralSuggested update - Profile file locationmemberTimothyP14 Oct '08 - 20:42 
Hi,
 
Might I suggest storing the profile file in the application data directory of the current user?
 
System.IO.Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), PROFILE_FILE_NAME)
 
As with the current solution, I attached a link to the Vista start menu after which the profile file could not be found.
The above solution requires more code, but is cleaner.
 
Great tool by the way
GeneralSwitchNetConfig a super prog - THANKSmemberpisoft22 May '08 - 10:56 
This is á super prog, thanks

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 7 May 2004
Article Copyright 2004 by Omar Al Zabir
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid