Programmatic Installation and Configuration of Microsoft Loopback Adapter

Windows systems have their own virtual network adapter called Microsoft Loopback Adapter (msloop). You can add it manually using the device manager – I wrote about this in my previous entry linked here or through the console with the Devcon tool. Devcon is a console version of the 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 a few versions of this tool depending on system architecture.

Note. For Windows Vista and 7 (64bit) use the amd64 version (not ia64).

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

  • to install the Microsoft Loopback Adapter (the 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 a static IP address use the 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 the Windows version this command can return the "Ok." string if it succeeds or nothing.

Note that for Vista and 7 (64bit), the network adapter must be enabled before setting the IP. For XP it is usually faster when used on a 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 ones 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 the device is connected)
  • Name, ProductName

The code

Example. The application shows how to make and use of the 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, and others after some changes) and redirect output to the 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 the QueryVirtualNetAdapters() function. Necessary methods are located in the 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 function like GetVtNicCount().

public static int GetVtNicCount()
{
    return QueryVirtualNetAdapters().Count;
}

To install the new Microsoft Loopback Adapter use the InstallNewVtNic() function. Installed devices can be automatically disabled by passing the 'enable device' argument as 'false'. The function returns DeviceID through the 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 the attachment for the complete code of the working example.


Similar Articles