select 网络适配器绑定到的国际化正确方法

Internationalisation-correct way to select network adapter to bind to

我有一个应用程序需要绑定到 "Microsoft Loopback Adapter"。我可以枚举所有网络设备并对友好名称执行字符串匹配,但是当然这在国际 Windows 变体上会失败。

识别正确网络适配器的正确方法是什么?

您担心对面向用户的字符串进行硬编码是对的。不仅本地化是一个问题,而且 Windows 7 中的字符串实际上发生了变化。因此 "Microsoft Loopback Adapter" 甚至不会匹配最近 OS.[=21= 的 en-US 版本]

您可以寻找的最佳不变式是网络接口的硬件 ID,即 *MSLOOP,包括文字星号。

一种方法是使用 INetCfg。要点是找到一个 INetCfgComponent,其中 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 或与将 GUID 映射到另一个标识符相关。

在伪代码中,这可能类似于:

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

如果您在 Windows 8 或更高版本上拥有 运行 的优势,则可以在 PowerShell 中轻松执行此操作:

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

从那里,您可以剥离任何有趣的属性,甚至直接进入其 IP 地址:

Get-NetAdapter | 
    Where ComponentID -eq '*msloop' | 
    Get-NetIPAddress -AddressFamily IPv4 |
    fl IPAddress