Microsoft Loopback Adapter - programmatically installation and configuration.


Windows systems have their own virtual network adapter called Microsoft Loopback Adapter (msloop). You can add it manually using device manager – I wrote about this in my previous entry linked here or through console with devcon tool. Devcon is a console version of device manager provided by Microsoft in WDK (Windows Driver Kit). For more information about it refer to http://support.microsoft.com/kb/311272. There are few versions of this tool depending on system architecture. 

Note: for Windows Vista and 7 (64bit) use amd64 version (not ia64).

Devcon is a handy way to list, disable, enable, install and remove of devices. You can use hardware ID with wildcards (*) or instance ID prefixed with @ as a commands parameters. Few examples:

  • to install Microsoft Loopback Adapter (device is enabled by default after installation)

    devcon install %WINDIR%\Inf\Netloop.inf *MSLOOP

  • to disable all of MS Loopback Adapters

    devcon disable *msloop


  • to enable specified adapter

    devcon enable @'ROOT\NET\0000


Note about install parameter: amd64 version (Vista, 7 64bit) of devcon will enable all other already installed msloop devices even if they were disabled (marked in example code).

To configure static IP address use Netsh command (standard Windows utility). According to online documentation "Netsh is a command-line scripting utility that allows you to, either locally or remotely, display or modify the network configuration of a computer that is currently running." More information is available here: http://technet.microsoft.com/en-us/library/cc738592(WS.10).aspx.

Command usage:

          netsh int ip set address name="Local Area Connection 2" static 192.168.0.3 255.255.255.0
(single line command)

Where 'name' is a NIC's connection name (can be obtained with WMI), '192.168.0.3' is an IP and '255.255.255.0' is a mask.

Depending on Windows version this command can return "Ok." string if succeed or nothing.
Note that for Vista and 7 (64bit) network adapter must be enabled before setting IP. For XP it is usually faster when used on disabled device (because of DHCP request).


The WMI class Win32_NetworkAdapter represents an IPv4 network adapter. It provides some useful properties used in example code to get connection name, instance ID and adapter state information. The full documentation link is here: http://msdn.microsoft.com/en-us/library/aa394216(VS.85).aspx. Be aware that many of this class's properties are not available on every Windows version. Important one's are:
  • NetConnectionID (returns connection name)
  • PNPDeviceID (returns instance ID)
  • ServiceName (i.e. msloop)
  • ConfigManagerErrorCode (for device state info)
  • NetConnectionStatus (for connection info)
  • MACAddress (returns MAC address if device is connected)
  • Name, ProductName

The code

Example application shows how to make and use of MSLoopbackTool utility class. The class code is not optimized but should work on most Windows systems (tested on XP and 7 64bit).
I have removed comments from code snippets here for better readability. Check attachment.

Function UseCommand() was created to execute external commands (devcon, netsh, other after some changes) and redirect output to application's console.


public static string UseCommand(CommandType  commandType, string command)

{

   //(...)

   lock (thisLock)

   {

       try

       {

           Process p = new Process();

           p.StartInfo.FileName = cfname;

           p.StartInfo.UseShellExecute = false;

           p.StartInfo.CreateNoWindow = true;

           p.StartInfo.RedirectStandardError = true;

           p.StartInfo.RedirectStandardOutput = true;

           p.StartInfo.Arguments = command;

           p.Start();

 

           if (p == null) return null;

           string stdOut = p.StandardOutput.ReadToEnd();

           p.WaitForExit(COMMAND_REPLY_TIMEOUT);

           return stdOut;

    }

   catch (Exception)

   {

           return null;

   }

   }

}


WMI access is provided by QueryVirtualNetAdapters() function. Necessary methods are located in System.Management namespace (System.Management.dll reference needed).


public static ManagementObjectCollection QueryVirtualNetAdapters()

{

    string serviceName = "msloop"; // Microsoft Loopback Adapter

    ManagementObjectSearcher searcher = new ManagementObjectSearcher(String.Format(

        "SELECT Name, NetConnectionID, PNPDeviceID, ConfigManagerErrorCode, NetConnectionStatus " +

        "FROM Win32_NetworkAdapter " +

        "WHERE ServiceName='{0}'",

        serviceName

        ));

    return searcher.Get();

}

 

This function is used in the example by every other helper functions like GetVtNicCount().

public static int GetVtNicCount()

{

    return QueryVirtualNetAdapters().Count;

}

To install new Microsoft Loopback Adapter use InstallNewVtNic() function. Installed device can be automatically disabled by passing 'enableDevice' argument as 'false'. Function returns DeviceID throught output parameter.

public static bool InstallNewVtNic(bool enableDevice, out string newDeviceID)

{

    string windir = Environment.GetEnvironmentVariable("windir");

    string command = string.Format(@"install {0}\Inf\Netloop.inf *MSLOOP", windir);

    newDeviceID = "";

    //(...)

    List<string> ldevices = GetVtNicPNPDeviceIDs(out lstate);

    UseCommand(CommandType.DEVCON, command);

    List<string> ldevicesVerify = GetVtNicPNPDeviceIDs();

    //(...)

    if (ldevicesVerify.Count > ldevices.Count)

    {

        for (int i = 0; i < ldevicesVerify.Count; i++)

        {

            if (!ldevices.Contains(ldevicesVerify[i]))

            {

                newDeviceID = ldevicesVerify[i];

                break;

            }

        }

        if (!enableDevice)

        {

            if (newDeviceID != "") DisableVtNic(newDeviceID);

        }

        return true;

    }

    return false;

}

To assign static IP to the adapter call SetVtNicIp() function. Basically all that has to be done is simple usage of netsh (for Vista and 7 the device must be enabled first).

public static bool SetVtNicIp(string PNPDeviceID, string ip, string mask)

{

    string cn = GetConnectionName(PNPDeviceID);  

    if (cn == null) return false;

 

    string command = string.Format(@"int ip set address name=""{0}"" static {1} {2}", cn, ip, mask)

 

    //(...)

    stdout = UseCommand(CommandType.NETSH, command);    ;

  

    //(...)

    if ((stdout != null) && (stdout.ToLower().Contains("ok") || stdout.Contains("")))

    {            

        return true;

    }

    return false;

}

Please see attachment for complete code of working example.

Up Next
    Ebook Download
    View all
    Learn
    View all