windows c语言获取所有网卡ip
时间: 2024-02-16 16:59:53 浏览: 137
在Windows系统下,可以使用GetAdaptersAddresses函数来获取所有网卡的IP地址。这个函数会返回一个链表,包含了所有网络接口的地址信息。下面是一个获取所有网卡IP地址的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>
#include <iphlpapi.h>
#pragma comment(lib, "IPHLPAPI.lib")
#pragma comment(lib, "Ws2_32.lib")
int main() {
PIP_ADAPTER_ADDRESSES pAddresses = NULL;
ULONG ulSize = 0;
// Make an initial call to GetAdaptersAddresses to get the necessary size into the ulSize variable
if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses, &ulSize) == ERROR_BUFFER_OVERFLOW) {
// Allocate memory for the adapter addresses
pAddresses = (PIP_ADAPTER_ADDRESSES) malloc(ulSize);
if (pAddresses == NULL) {
printf("Error allocating memory needed to call GetAdaptersAddresses\n");
return 1;
}
// Get the adapter addresses
if (GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses, &ulSize) == NO_ERROR) {
PIP_ADAPTER_ADDRESSES pCurrAddresses = pAddresses;
while (pCurrAddresses) {
printf("%S:\n", pCurrAddresses->FriendlyName);
// Walk through the list of IP addresses for this adapter
PIP_ADAPTER_UNICAST_ADDRESS pUnicast = pCurrAddresses->FirstUnicastAddress;
while (pUnicast) {
struct sockaddr_in *pAddr = (struct sockaddr_in *) pUnicast->Address.lpSockaddr;
printf("\t%s\n", inet_ntoa(pAddr->sin_addr));
pUnicast = pUnicast->Next;
}
pCurrAddresses = pCurrAddresses->Next;
}
} else {
printf("Error calling GetAdaptersAddresses\n");
return 1;
}
free(pAddresses);
} else {
printf("Error calling GetAdaptersAddresses\n");
return 1;
}
return 0;
}
```
这个代码会遍历所有网卡,打印出每个网卡的名称和对应的IP地址。注意,这个代码需要在Windows系统下编译运行,并且需要链接IPHLPAPI.lib和Ws2_32.lib两个库文件。
阅读全文