C++启用禁用网卡的代码
时间: 2023-11-01 18:07:41 浏览: 255
以下是使用C++实现启用禁用网卡的示例代码:
```c++
#include <WinSock2.h>
#include <Iphlpapi.h>
#include <iostream>
#pragma comment(lib, "iphlpapi.lib")
int main() {
// 获取所有网卡信息
DWORD dwSize = 0;
DWORD dwRetVal = 0;
PIP_ADAPTER_INFO pAdapterInfo = NULL;
GetAdaptersInfo(NULL, &dwSize);
pAdapterInfo = (PIP_ADAPTER_INFO)malloc(dwSize);
if (pAdapterInfo == NULL) {
std::cout << "Failed to allocate memory for adapter info" << std::endl;
return 1;
}
if (GetAdaptersInfo(pAdapterInfo, &dwSize) != ERROR_SUCCESS) {
std::cout << "Failed to get adapter info" << std::endl;
free(pAdapterInfo);
return 1;
}
// 输出所有网卡信息并让用户选择
std::cout << "Available network adapters:" << std::endl;
PIP_ADAPTER_INFO currentAdapter = pAdapterInfo;
int adapterIndex = 0;
while (currentAdapter) {
std::cout << adapterIndex << ". " << currentAdapter->AdapterName << " - " << currentAdapter->Description << std::endl;
currentAdapter = currentAdapter->Next;
adapterIndex++;
}
std::cout << "Enter the index of the adapter to enable/disable (0-" << adapterIndex - 1 << "): ";
int chosenIndex;
std::cin >> chosenIndex;
if (chosenIndex < 0 || chosenIndex >= adapterIndex) {
std::cout << "Invalid adapter index" << std::endl;
free(pAdapterInfo);
return 1;
}
currentAdapter = pAdapterInfo;
for (int i = 0; i < chosenIndex; i++) {
currentAdapter = currentAdapter->Next;
}
// 获取网卡状态并启用/禁用
MIB_IFROW ifRow;
memset(&ifRow, 0, sizeof(ifRow));
ifRow.dwIndex = currentAdapter->Index;
dwRetVal = GetIfEntry(&ifRow);
if (dwRetVal != NO_ERROR) {
std::cout << "Failed to get interface info" << std::endl;
free(pAdapterInfo);
return 1;
}
if (ifRow.dwAdminStatus == IF_ADMIN_STATUS_UP) {
std::cout << "Disabling adapter..." << std::endl;
ifRow.dwAdminStatus = IF_ADMIN_STATUS_DOWN;
} else {
std::cout << "Enabling adapter..." << std::endl;
ifRow.dwAdminStatus = IF_ADMIN_STATUS_UP;
}
dwRetVal = SetIfEntry(&ifRow);
if (dwRetVal != NO_ERROR) {
std::cout << "Failed to set interface info" << std::endl;
free(pAdapterInfo);
return 1;
}
std::cout << "Success!" << std::endl;
free(pAdapterInfo);
return 0;
}
```
上述代码使用Winsock API和IP Helper API获取网卡信息,并允许用户选择要启用/禁用的网卡。然后,它使用SetIfEntry函数启用/禁用选定的网卡。注意,此方法仅适用于Windows操作系统。
阅读全文