废话不多说,直接上代码:
#include <WinSock2.h>
#include <Iphlpapi.h>
#include <iostream>
using namespace std;
#pragma comment(lib,"Iphlpapi.lib") //需要添加Iphlpapi.lib库
int main(int argc, char* argv[])
{
PIP_ADAPTER_INFO pIpAdapterInfo = new IP_ADAPTER_INFO();
unsigned long stSize = sizeof(IP_ADAPTER_INFO);
int nRel = GetAdaptersInfo(pIpAdapterInfo, &stSize);
int netCardNum = 0;
int IPnumPerNetCard = 0;
if (ERROR_BUFFER_OVERFLOW == nRel){
delete pIpAdapterInfo;
pIpAdapterInfo = (PIP_ADAPTER_INFO)new BYTE[stSize];
nRel = GetAdaptersInfo(pIpAdapterInfo, &stSize);
}
if (ERROR_SUCCESS == nRel){
while (pIpAdapterInfo) {
cout << "网卡名称:" << pIpAdapterInfo->AdapterName << endl;
do{
HKEY cpp_key;
std::string cpp_data = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\";
cpp_data += pIpAdapterInfo->AdapterName;
cpp_data += "\\Connection";
if (ERROR_SUCCESS == RegOpenKeyExA(HKEY_LOCAL_MACHINE, cpp_data.c_str(), 0, KEY_READ, &cpp_key)){
DWORD NameSize, NameCnt, NameMaxLen, Type;
DWORD KeyCnt, KeyMaxLen, DateSize, MaxDateLen;
if (ERROR_SUCCESS == RegQueryInfoKeyA(cpp_key, NULL, NULL, 0, &KeyCnt, &KeyMaxLen, NULL, &NameCnt, &NameMaxLen, &MaxDateLen, NULL, NULL)){
for (DWORD dwIndex = 0; dwIndex < NameCnt; dwIndex++){
DateSize = MaxDateLen + 1;
NameSize = NameMaxLen + 1;
char *szValueName = (char *)malloc(NameSize);
LPBYTE szValueDate = (LPBYTE)malloc(DateSize);
RegEnumValueA(cpp_key, dwIndex, szValueName, &NameSize, NULL, &Type, szValueDate, &DateSize);//读取键值
//cout << szValueName << " " << szValueDate << endl;
if (strcmp(szValueName, "Name") == 0){
cout << szValueDate << endl;
free(szValueName);
free(szValueDate);
break;
}
else{
free(szValueName);
free(szValueDate);
}
}
}
else{
cout << "读取子键失败!" << endl;
}
}
else{
cout << "打开注册表失败!" << endl;
}
RegCloseKey(cpp_key);//关闭句柄
} while (0);
IP_ADDR_STRING *pIpAddrString = &(pIpAdapterInfo->IpAddressList);
cout << "IP 地址:" << pIpAddrString->IpAddress.String << endl;
cout << "子网地址:" << pIpAddrString->IpMask.String << endl;
cout << "网关地址:" << pIpAdapterInfo->GatewayList.IpAddress.String << endl;
pIpAdapterInfo = pIpAdapterInfo->Next;
cout << "--------------------------------------------------------------------" << endl;
}
}
if (pIpAdapterInfo){
delete pIpAdapterInfo;
}
system("pause");
return 0;
}
由于GetAdaptersInfo获取出来的网卡适配器名称是一个UUID,拿不到真正的“本地连接”、“以太网”这样的名称,但是cmd命令设置网卡IP必须用“本地连接”、“以太网”这个名字,所以不得不想办法找到这个UUID对应的名称。
对比了下Windows10和Windows7,网卡信息存放在注册表中的未知都是一样的,都在“SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}”下(本来以为后面这个UUID是不确定的),在这个小面,可以找到GetAdaptersInfo中的网卡名称,注册表中,字段Name的值就是控制面板中显示的网络的名称(以太网、本地连接等)。