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   
Generalimplementationmembereabidi775 Sep '07 - 11:06 
Hi,
i have implemented your fantastic software (a heaven for me 'cause i frequently change network settings). Right for this reason, i have made some change to your code, and if you want you could view the changes and update your article. Basically i've added a notify icon so you can switch between network configuration in a click, and manage also firefox network configuration. Also, you can edit the default search engines of firefox.
 
Emanuele
GeneralRe: implementationmemberOmar Al Zabir5 Sep '07 - 16:40 
Please email me the code at OmarALZabir at gmail.com and I will update the article with your changes.
 
Thank you very much.

 
Regards,
Omar AL Zabir
Visual C# MVP

GeneralHelpfulmembererwin satrya20 Aug '07 - 3:38 
Wonderfully helpful
 
to infinity and beyond

QuestionDHCP IP/Static DNSmemberDavid Dreggors5 Feb '07 - 16:30 
I have looked at many C# implementations of a network configuration tool. While yours is nicely done and cleanly coded, it seems to be missing a major function as do all others I have seen. I may just be blind, but I cannot seem to find a clean function using WMI or API (not registry) that can lookup weather you pull your DNS from the DHCP Server if set to "Obtain IP Address Automatically" or if DNS is set to Static. In the windows tool you can specify DNS servers even if you get your IP from DHCP yet the WMI doesn't seem to have a property or method to return these settings. Can you help me on this one?
GeneralProblem with multiple IP addressesmemberp0rkskratchin25 Jan '07 - 22:59 
If you specify multiple IP address (comma seperated), then the application will not change the IP address.
 
I'm using this otherwise excellent code to create a network management CmdLet for Powershell, and if I specify multiple IPs, I get a return code of '90' from WMI, which for the EnableStatic method, means 'Parameter out of bounds'. I then downloaded this app, and discovered it also will not deal with multiple, comma-seperated IPs.
 
I'm trying to find a fix, and if I do, i'll post it here.
 
M
AnswerRe: Problem with multiple IP addressesmemberChris Tynes6 Feb '07 - 19:56 
First, kudos to Omar for spending the time to develop something that is still referenced almost 3 years later.
 
I ran into the multiple IP addresses issues initially as well. Simply change the line:
      newIP[ "SubnetMask" ] = new string[] { SubnetMask };
to
      newIP[ "SubnetMask" ] = SubnetMask.Split(',');
 
Reason: There has to be one entry in the SubnetMask array to correspond with each entry in the IPAddress property specified by:
      newIP[ "IPAddress" ] = IpAddresses.Split( ',' );
 
I'm pretty sure the same relationship exists between DefaultIPGateway and GatewayCostMetric as well.
 
It's a late reply, but maybe this will benefit somebody down the road.
GeneralLittle suggestmemberThomas.Mueller66 Sep '06 - 6:32 
Great tools. Helps me a lot !
 
One thing I found in the sources:
 
You can specify multiple IP addresses in one profile, just
comma separated.
 
Do so also with the subnet mask when applying changes,
which may also vary with IP:
 
newIP[ "SubnetMask" ] = SubnetMask.Split( ',' );
//old: newIP[ "SubnetMask" ] = new string[] { SubnetMask });
 
A small simple change. Works now fine !
 

GeneralConvert this to VB.NETmembermrodriguezc1 Jun '06 - 8:00 
I tried to make this code on VB. NET, Im pretty new with this, and I cant go on because I cant convert the system.string[] into a normal string, I have everything equal, and when I make this:
 
For Each mgr As ManagementObject In management.GetInstances()
If mgr.Item("IPEnabled") Then
txtDireccionIP = mgr.Item("IPAddress").ToString()
Exit For
End If
 
txtDireccionIP variable just show system.string[], why? because is an array?, I tried split it, get elements but nothing, what Im missing?
 
Thanks everyone...

 
Mauricio Rodriguez
newbie
GeneralApplication Errormemberroundi21 May '06 - 1:34 
Hello,
I am getting this error:
 
The application failed to initialize properly (0xc0000135)
 
Any ideas?
 
Txs
roundi
GeneralWonderfulmembertuca.ssa13 Mar '06 - 1:07 
This work is very fantastic...Works fine.. Thaks...Big Grin | :-D Laugh | :laugh: Laugh | :laugh:
 
Tuca From Bahia
GeneralSetIP only works for Gatewaymembermystique200028 Sep '05 - 6:36 
I copy/pasted the source code of the method SetIP() and in my application only the gateway gets set the the input value. Why?
GeneralAlternative network setting causes problemmemberFrank Esser24 Aug '05 - 23:50 
Just a little problem that came up using your code:
I have a PC with DHCP setting but an alternative IP-address setting (Windows XP).
When the DHCP server is down then the PC starts with the alternative IP-address.
In this case the application shows nothing as current configuration.
 
How can I fix this?
 
Anyway it is a very useful code, thanks for it !!!
GeneralVB 6 VersionmemberJeiel Borner22 Aug '05 - 8:31 
Could you post up a vb6 version or a link to it?
QuestionCould u post a vc6 demo?memberTcpip200521 Aug '05 - 22:45 
I tried to do the same thing in vc6 since I don't have vs.net,and I don't understand c#.
I used ultraedit to do so. But it is realy difficult. finally i gave up.
could you please post a vc6 demo here? no matter how simple it is.
Thank you very much. My best regards.
 
Alick
AnswerRe: Could u post a vc6 demo?memberTcpip200521 Aug '05 - 22:49 
I don't care about XML Serialization.
What I want is just the setting. I mean ip,gate,mask,dns,proxy settings.
Nothing else.
 
Much thanks.
 
Alick
GeneralgreatmemberthomasFo17 Aug '05 - 23:39 
this is what i was lookingn for.
Good documentation.
 
Thomas
Questiondoes this assume all networks have the same workgroup or domain?memberdatamodel10 Aug '05 - 19:10 
What if the office LAN uses a workgroup other than that used in the home network? Does this application address this at all? Thanks. Good work.
GeneralDisable network adapterssussAnonymous24 Jun '05 - 10:56 
What about disable the network adapters unused in some profiles?
GeneralXML questionsmemberTom Wright18 May '05 - 6:43 
Can you help me understand how you are writing out the XML stuff?
 
I'm having trouble understanding what you are doing in this code:

if( DialogResult.OK == newProfileDialog.ShowDialog( this ) )
{
// create a new profile object
Profile newProfile = new Profile( newProfileDialog.NewProfileName );
_Profiles.Add( newProfile );
 
// show it in the drop down as selected
cboProfiles.SelectedIndex = cboProfiles.Items.Add( newProfile.Name );
 
// load the NIC list
loadNICs();
}
 

I see that you are opening your new profile dialog box so that the user can type in the new profile name, but I'm not sure how you are saving that to the XML file.
 
Do you first create the new profile with just the profile name then write out the different NIC attributes?
 
Also why not just store the profile and the attributes for the NIC that was choosen? I see that your storing all the NIC's attributes.
 
Thanks
 

 
Tom Wright
tawright915@yahoo.com
GeneralRe: XML questionsmemberOmar Al Zabir18 May '05 - 21:38 
Save is done from:
 
ConfigurationHelper.SaveConfig() function.
GeneralRe: XML questionsmemberTom Wright19 May '05 - 11:56 
So can you please help me understand what it is that you are doing in the code that I listed?
 
Thanks

 
Tom Wright
tawright915@yahoo.com
GeneralRe: XML questionsmemberTom Wright26 May '05 - 12:10 
Still having trouble understanding how you are writing out your nic profiles. I am able to create the file and put my profile name in it but I cannot seem to get it to write out the nic profiles. Where in your code are you setting the profiles for each nic. I see that you are saving them when you see the event Form closing. But where in the code are you loading up the _NICProfile array and where are you writing it out too?
 
Are you making two calls to the XML serializer, one for the profile and one when you want to write out the nic info?
 
By the way cool website. Checked it out and was very impressed.
 
Thanks
 
Tom Wright
tawright915@yahoo.com
Generalempty gatewaymembersuorttex5 May '05 - 21:04 
How can i remove gateway? or set addresses without GW?
 
-suortti
QuestionOption to switch WorkGroup?sussAnonymous26 Jan '05 - 4:00 
It would be great if we could change our Workgroup settings too - this is important as I belong to different workgroups which I still have to change manually...
GeneralRequires .NET. Too bad.membersssnc7 Dec '04 - 21:26 
I guess that's what this forums is all about, so I can't complain too much, but I was surfing for a small footprint network switcher and I thought I'd found it. But this requires .NET, which I've intentionally not installed yet: I don't think M$ has any idea where it's going with it and until it does, I'm now slowing my machine down with it.
 
So I'll continue my search for a little 'net profile switcher.

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130516.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