Click here to Skip to main content
6,822,613 members and growing! (15,648 online)
Email Password   helpLost your password?
Languages » C# » Applications     Intermediate License: The Code Project Open License (CPOL)

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

By Omar Al Zabir

A handy utility for laptop users which stores network and proxy configuration as profiles and apply a profile very quickly whenever laptop goes to a different network
C#, Windows, .NET1.1VS.NET2003, Dev
Posted:6 May 2004
Views:168,238
Bookmarked:135 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
50 votes for this article.
Popularity: 7.49 Rating: 4.41 out of 5
2 votes, 4.0%
1

2
2 votes, 4.0%
3
7 votes, 14.0%
4
39 votes, 78.0%
5

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


Member
I am: Chief Architect, SaaS Platform, BT Innovate & Design (British Telecom). Visual C# MVP '05-'07, ASP.NET MVP '08
I was: Co-founder & CTO, Pageflakes(www.pageflakes.com)

My Blog: http://msmvps.com/blogs/omar/
My Specialization: Web 2.0 Rich AJAX Applications, Level 3 SaaS, Performance and Scalability of Web Apps.
My Book: Building a Web 2.0 portal using ASP.NET 3.5. Also on Amazon
My Email: OmarALZabir at gmail dot com
My Interest: Travel, Performance and Scalability Challenges.
My Projects:
Open Source Web 2.0 AJAX Portal
Smart UML - Freehand UML Designer
RSS Aggregator both Outlook and Standalone
Store Front in JSP but ASP.NET style

My Articles:
99.99% Available Production Architecture
Build GoogleIG like Ajax Start Page in 7 days
10 ASP.NET Performance and Scalability Secrets
ASP.NET AJAX under the hood secrets
UFrame: goodness of UpdatePanel and IFRAME combined
Fast ASP.NET web page loading
Fast, Scalable, Streaming AJAX Proxy
Using COM safely inside "using" block without requiring interop assembly
Implementing Word Like Automation Model
Distributed Command Pattern
StickOut - .NET 2.0, VSTS, Outlook Addin,
Occupation: Architect
Company: British Telecom
Location: Bangladesh Bangladesh

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 56 (Total in Forum: 56) (Refresh)FirstPrevNext
GeneralLoad/Save method Pinmemberanen19:47 30 Jan '10  
GeneralVery nice! Pinmemberquicoli2:48 1 Jul '09  
GeneralRe: Very nice! PinmvpOmar Al Zabir7:03 1 Jul '09  
GeneralThanks! Pinmemberlegolasgreenleaf2:51 3 Apr '09  
GeneralWell Buillt Utility PinmemberKannan.P0:37 13 Jan '09  
GeneralSuggested update - Profile file location PinmemberTimothyP21:42 14 Oct '08  
GeneralSwitchNetConfig a super prog - THANKS Pinmemberpisoft11:56 22 May '08  
GeneralAmazing PinmemberJonathan C Dickinson21:36 13 May '08  
GeneralI guess you have still have lot more things to share.. Pinmemberjavedahassan10:05 6 Feb '08  
GeneralVista Business PinmemberEdcel Kahayon22:36 23 Jan '08  
GeneralRe: Vista Business PinmemberNordin Rahman23:42 4 Mar '08  
GeneralHello! Pinmemberadri68ro19:32 12 Dec '07  
GeneralRe: Hello! PinmemberGeorge Thackray7:38 8 Oct '09  
QuestionNOT WORKING WITH VISTA Pinmemberoussamaghanem22:29 21 Oct '07  
AnswerRe: NOT WORKING WITH VISTA PinmemberTimothyP21:38 14 Oct '08  
AnswerRe: NOT WORKING WITH VISTA PinmemberOmar Al Zabir21:59 14 Oct '08  
Generalimplementation Pinmembereabidi7712:06 5 Sep '07  
GeneralRe: implementation PinmemberOmar Al Zabir17:40 5 Sep '07  
GeneralHelpful Pinmembererwin satrya4:38 20 Aug '07  
QuestionDHCP IP/Static DNS PinmemberDavid Dreggors17:30 5 Feb '07  
GeneralProblem with multiple IP addresses Pinmemberp0rkskratchin23:59 25 Jan '07  
AnswerRe: Problem with multiple IP addresses PinmemberChris Tynes20:56 6 Feb '07  
GeneralLittle suggest PinmemberThomas.Mueller67:32 6 Sep '06  
GeneralConvert this to VB.NET Pinmembermrodriguezc9:00 1 Jun '06  
GeneralApplication Error Pinmemberroundi2:34 21 May '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.

PermaLink | Privacy | Terms of Use
Last Updated: 6 May 2004
Editor: Nishant Sivakumar
Copyright 2004 by Omar Al Zabir
Everything else Copyright © CodeProject, 1999-2010
Web18 | Advertise on the Code Project