0

I have an application which needs to bind to a "Microsoft Loopback Adapter". I can enumerate all the network devices and perform a string match on the friendly name, but of course this will fail on international Windows variants.

What is the correct way to identify the right network adapter?

Martin Thompson
  • 16,395
  • 1
  • 38
  • 56

1 Answers1

2

You're right to worry about hard-coding the user-facing string. Not only is localization a problem, but the string actually changed in Windows 7. So "Microsoft Loopback Adapter" won't even match on an en-US version of a recent OS.

The best invariant you can look for is the hardware ID of the network interface, which is *MSLOOP, including the literal asterisk.

One approach is to use INetCfg. The gist is to find an INetCfgComponent where its GetId method returns the string "*msloop". Once you know the matching component, you can query its GUID from GetInstanceGuid. That GUID uniquely identifies the NIC in many networking APIs. If you need to convert the GUID to some other identifier (like ifAlias or NET_LUID), then you can use GetIfTable2Ex or related to map the GUID to the other identifier.

In pseudocode, that might resemble:

CoInitializeEx
CoCreateInstance(CLSID_CNetCfg, 0, CLSCTX_SERVER, IID_PPV_ARGS(&netcfg));
netcfg->Initialize(0)
netcfg->EnumComponents(GUID_DEVCLASS_NET, &enumerator)
while (S_OK == enumerator->Next(1, &component, 0))
    component->GetId(&id)
    if (id case-insensitive-match "*msloop")
        component->GetInstanceGuid(result)
        print "Windows loopback adapter: " + result

If you have the luxury of running on Windows 8 or later, this can be executed quite easily in PowerShell:

Get-NetAdapter | Where ComponentID -eq '*msloop'

From there, you can peel off any interesting properties, or even go straight to its IP address:

Get-NetAdapter | 
    Where ComponentID -eq '*msloop' | 
    Get-NetIPAddress -AddressFamily IPv4 |
    fl IPAddress
Jeffrey Tippet
  • 3,146
  • 1
  • 14
  • 15