Windows系统下枚举本机物理网卡

#include <winsock2.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <iostream>
#include <string>
#include<windows.h>

#pragma comment(lib,"Iphlpapi.lib")

using namespace std;

int main(int argc, char *argv[])
{
//typedef IP_ADAPTER_ADDRESSES* PIP_ADAPTER_ADDRESSES

PIP_ADAPTER_ADDRESSES pAddresses;
ULONG outBufLen = 0;
DWORD dwRetVal = 0;

pAddresses = (IP_ADAPTER_ADDRESSES*)malloc(sizeof(IP_ADAPTER_ADDRESSES));

// Make an initial call to GetAdaptersAddresses to get the size needed into the outBufLen variable
//初始调用GetAdaptersAddresses以将所需的大小放入outBufLen变量中
if (GetAdaptersAddresses(AF_INET, 0, NULL, pAddresses, &outBufLen)
== ERROR_BUFFER_OVERFLOW) {

//std::cout<< "Make an initial call to GetAdaptersAddresses. "<< std::endl;
free(pAddresses);
pAddresses = (IP_ADAPTER_ADDRESSES*)malloc(outBufLen);
}

// Make a second call to GetAdaptersAddresses to get the actual data we want

if ((dwRetVal = GetAdaptersAddresses(AF_INET,
0,
NULL,
pAddresses,
&outBufLen)) == NO_ERROR) {
// If successful, output some information from the data we received

//std::cout << "Make a second call to GetAdaptersAddresses. " << std::endl;

PIP_ADAPTER_ADDRESSES pCurrAddresses = pAddresses;
string str1 = "Mellanox ConnectX-5";
while (pCurrAddresses) {
//这个Friendly name不知道打印的是什么,没有结果,注释掉
//printf("\tFriendly name: %S\n", pCurrAddresses->FriendlyName);

wchar_t *WStr = pCurrAddresses->Description;

size_t len = wcslen(WStr + 1);

size_t converted = 0;

char* CStr = (char*)malloc(len);

wcstombs_s(&converted,CStr,len,WStr,_TRUNCATE);

CStr[len] = 0;

string str2 = CStr;

cout << str2 << endl;
//printf("\tDescription1: %S\n", WStr);
int a=strspn(str1.c_str(),CStr);
cout << a << endl;


pCurrAddresses = pCurrAddresses->Next;
}
}
else {
printf("Call to GetAdaptersAddresses failed.\n");
LPVOID lpMsgBuf;
if (FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwRetVal,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language

(LPTSTR)&lpMsgBuf,
0,
NULL)) {
std::cout << "\tError: %s"<< lpMsgBuf << std::endl;
}
LocalFree(lpMsgBuf);
}
free(pAddresses);

system("pause");

return 0;
}

posted @ 2020-05-08 21:40  大哥放过我  阅读(621)  评论(0)    收藏  举报