// 开启/关闭网卡协议
// adapterName Realtek PCIe GbE Family Controller
// protocolName ms_tcpip6 (ipv6)可以通过PowerShell命令查看Get-NetAdapterBinding
// enable true/false
void enableAdapterProtocol(const WCHAR* adapterName, const WCHAR* protocolName, bool enable)
{
CComPtr<INetCfg> pCfg = NULL;
CComPtr<INetCfgComponent> pCfgComponent = NULL;
CComPtr<IEnumNetCfgBindingPath> pEnumNetCfgBindingPath = NULL;
CComPtr<INetCfgBindingPath> pCfgBindingPath = NULL;
CComPtr<IEnumNetCfgBindingInterface> pEnumNetCfgBindingInterface = NULL;
CComPtr<INetCfgBindingInterface> pCfgBindingInterface = NULL;
CComPtr<INetCfgComponentBindings> pCfgComponentBindings = NULL;
CComPtr<INetCfgComponent> pCfgComponent2 = NULL;
CComPtr<INetCfgLock> pCfgLock = NULL;
LPWSTR lpszApp = NULL;
ULONG ulCount = 0;
HRESULT hr = S_OK;
LPWSTR lpszItemName = NULL;
//GUID guid;
hr = CoCreateInstance(CLSID_CNetCfg, NULL, CLSCTX_INPROC_SERVER,IID_INetCfg, (void**)&pCfg);
if (hr != S_OK)
goto finish;
hr = pCfg->QueryInterface(IID_INetCfgLock, (LPVOID*)&pCfgLock);
if (hr != S_OK)
goto finish;
// win7需要AcquireWriteLock
hr = pCfgLock->AcquireWriteLock(5000, L"SERVER", &lpszApp);
if (hr != S_OK)
goto finish;
hr = pCfg->Initialize(NULL);
if (hr != S_OK)
goto finish;
hr = pCfg->FindComponent(protocolName, &pCfgComponent);
if (hr != S_OK)
goto finish;
//GUID_DEVCLASS_NETTRANS
//pCfgComponent->GetClassGuid(&guid);
hr = pCfgComponent->QueryInterface(IID_INetCfgComponentBindings, (void**)&pCfgComponentBindings);
if (hr != S_OK)
goto finish;
hr = pCfgComponentBindings->EnumBindingPaths(EBP_BELOW, &pEnumNetCfgBindingPath);
if (hr != S_OK)
goto finish;
while (true)
{
hr = pEnumNetCfgBindingPath->Next(1, &pCfgBindingPath, &ulCount);
if (hr != S_OK)
break;
hr = pCfgBindingPath->EnumBindingInterfaces(&pEnumNetCfgBindingInterface);
if (hr == S_OK)
{
ULONG ulCount1 = 0;
while (true)
{
hr = pEnumNetCfgBindingInterface->Next(1, &pCfgBindingInterface, &ulCount1);
if (hr != S_OK)
break;
hr = pCfgBindingInterface->GetLowerComponent(&pCfgComponent2);
if (hr == S_OK)
{
hr = pCfgComponent2->GetDisplayName(&lpszItemName);
if (hr == S_OK)
{
if (wcsncmp(lpszItemName, adapterName, wcslen(adapterName)) == 0)
{
hr = pCfgBindingPath->Enable(enable);
if (hr == S_OK)
{
pCfg->Apply();
}
}
CoTaskMemFree(lpszItemName);
lpszItemName = NULL;
}
}
pCfgBindingInterface = NULL;
pCfgComponent2 = NULL;
}
}
pCfgBindingPath = NULL;
pEnumNetCfgBindingInterface = NULL;
}
finish:
if (lpszItemName != NULL)
{
CoTaskMemFree(lpszItemName);
lpszItemName = NULL;
}
if (pCfgLock != NULL)
{
pCfgLock->ReleaseWriteLock();
pCfgLock = NULL;
}
if (lpszApp != NULL)
{
CoTaskMemFree(lpszApp);
lpszApp = NULL;
}
}
C++代码实现禁用网卡IPV6协议
于 2025-05-28 09:44:56 首次发布
2059

被折叠的 条评论
为什么被折叠?



