源代码:(一)
bool SetInterfaceName(int interface_index, const std::string& interface_name) noexcept
{
if (interface_index < 0 || interface_name.empty())
{
return false;
}
SYSTEM_WINDOWS_COM_INITIALIZED WINDOWS_COM_INITIALIZED;
_bstr_t bstr_interface_name = interface_name.data();
return RenameAdapterByIndexWMI(interface_index, bstr_interface_name.GetBSTR());
}
源代码:(二)
/* https://devops-collective-inc.gitbook.io/windows-powershell-networking-guide/renaming-the-network-adapter */
static bool RenameAdapterByIndexWMI(DWORD dwIndex, LPCWSTR lpNewName) noexcept
{
HRESULT hr = S_OK;
// 创建 WMI 服务
IWbemLocator* pLoc = NULL;
hr = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID*)&pLoc);
if (FAILED(hr))
{
return false;
}
IWbemServices* pSvc = NULL;
hr = pLoc->ConnectServer(_bstr_t(L"ROOT\\CIMV2"), NULL, NULL, 0, NULL, 0, 0, &pSvc);
if (FAILED(hr))
{
pLoc->Release();
return false;
}
// 设置 WMI 服务安全级别
hr = CoSetProxyBlanket(pSvc, RPC_C_AUTHN_WINNT, RPC_C_AUTHZ_NONE, NULL, RPC_C_AUTHN_LEVEL_CALL, RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE);
if (FAILED(hr))
{
pSvc->Release();
pLoc->Release();
return false;
}
// 构建 WQL 查询语句
WCHAR wszQuery[512];
swprintf_s(wszQuery, _countof(wszQuery), L"SELECT * FROM Win32_NetworkAdapter WHERE InterfaceIndex='%u'", dwIndex);
// 查询符合条件的网卡对象
IEnumWbemClassObject* pEnumerator = NULL;
hr = pSvc->ExecQuery(_bstr_t(L"WQL"), _bstr_t(wszQuery), WBEM_FLAG_FORWARD_ONLY, NULL, &pEnumerator);
if (FAILED(hr) || NULL == pEnumerator)
{
pSvc->Release();
pLoc->Release();
return false;
}
// 获取匹配的第一个网卡对象
IWbemClassObject* pNetAdapter = NULL;
ULONG uReturned = 0;
hr = pEnumerator->Next(WBEM_INFINITE, 1, &pNetAdapter, &uReturned);
if (FAILED(hr) || NULL == pNetAdapter || uReturned == 0)
{
pEnumerator->Release();
pSvc->Release();
pLoc->Release();
return false;
}
VARIANT vtName;
memset(&vtName, 0, sizeof(vtName));
// 将新的网卡名称转换为可写字符串,并设置 Name 属性
WCHAR* pName = _wcsdup(lpNewName);
vtName.vt = VT_BSTR;
vtName.bstrVal = SysAllocString(pName);
if (NULL != pName)
{
free(pName);
}
hr = pNetAdapter->Put(L"NetConnectionID", 0, &vtName, CIM_STRING);
if (FAILED(hr))
{
VariantClear(&vtName);
pEnumerator->Release();
pNetAdapter->Release();
pSvc->Release();
pLoc->Release();
return false;
}
// 更新网卡对象
hr = pSvc->PutInstance(pNetAdapter, WBEM_FLAG_UPDATE_ONLY, NULL, NULL);
if (FAILED(hr))
{
VariantClear(&vtName);
pEnumerator->Release();
pNetAdapter->Release();
pSvc->Release();
pLoc->Release();
return false;
}
// 释放资源
VariantClear(&vtName);
pEnumerator->Release();
pNetAdapter->Release();
pSvc->Release();
pLoc->Release();
return true;
}