从IPv4地址获取networking接口名称

给定一个IPv4地址,我怎样才能获得其相关的networking接口名称,如“以太网适配器本地连接”,在Windows中使用C + +? 或者,如何获得本地计算机的networking接口名称和IPv4地址列表? 我只能使用getaddrinfoinet_ntoa获取IPv4地址。

Solutions Collecting From Web of "从IPv4地址获取networking接口名称"

 #include <windows.h> #include <iphlpapi.h> #include <stdio.h> #pragma comment(lib, "iphlpapi.lib") int main(int argc, char** argv) { PIP_ADAPTER_INFO pAdapterInfo; pAdapterInfo = (IP_ADAPTER_INFO *) malloc(sizeof(IP_ADAPTER_INFO)); ULONG buflen = sizeof(IP_ADAPTER_INFO); if(GetAdaptersInfo(pAdapterInfo, &buflen) == ERROR_BUFFER_OVERFLOW) { free(pAdapterInfo); pAdapterInfo = (IP_ADAPTER_INFO *) malloc(buflen); } if(GetAdaptersInfo(pAdapterInfo, &buflen) == NO_ERROR) { PIP_ADAPTER_INFO pAdapter = pAdapterInfo; while (pAdapter) { printf("\tAdapter Name: \t%s\n", pAdapter->AdapterName); printf("\tAdapter Desc: \t%s\n", pAdapter->Description); printf("\tAdapter Addr: \t%ld\n", pAdapter->Address); printf("\tIP Address: \t%s\n", pAdapter->IpAddressList.IpAddress.String); printf("\tIP Mask: \t%s\n", pAdapter->IpAddressList.IpMask.String); printf("\tGateway: \t%s\n", pAdapter->GatewayList.IpAddress.String); if(pAdapter->DhcpEnabled) { printf("\tDHCP Enabled: Yes\n"); printf("\t\tDHCP server: \t%s\n", pAdapter->Dhcpserver.IpAddress.String); printf("\tLease Obtained: %ld\n", pAdapter->LeaseObtained); } else { printf("\tDHCP Enabled: No\n"); } if(pAdapter->HaveWins) { printf("\tHave Wins: Yes\n"); printf("\t\tPrimary Wins server: \t%s\n", pAdapter->PrimaryWinsserver.IpAddress.String); printf("\t\tSecondary Wins server: \t%s\n", pAdapter->SecondaryWinsserver.IpAddress.String); } else { printf("\tHave Wins: No\n"); } pAdapter = pAdapter->Next; } } else { printf("Call to GetAdaptersInfo failed.\n"); } } 

我也会分享我最小的版本:

 #include <windows.h> #include <iphlpapi.h> #include <stdio.h> #pragma comment(lib, "iphlpapi.lib") int main() { ULONG buflen = sizeof(IP_ADAPTER_INFO); IP_ADAPTER_INFO *pAdapterInfo = (IP_ADAPTER_INFO *)malloc(buflen); if (GetAdaptersInfo(pAdapterInfo, &buflen) == ERROR_BUFFER_OVERFLOW) { free(pAdapterInfo); pAdapterInfo = (IP_ADAPTER_INFO *)malloc(buflen); } if (GetAdaptersInfo(pAdapterInfo, &buflen) == NO_ERROR) { for (IP_ADAPTER_INFO *pAdapter = pAdapterInfo; pAdapter; pAdapter = pAdapter->Next) { printf("%s (%s)\n", pAdapter->IpAddressList.IpAddress.String, pAdapter->Description); } } if (pAdapterInfo) free(pAdapterInfo); return 0; }