In Windows C++, you can list all network interfaces along with their IPv4 and IPv6 addresses using the Windows Sockets API (Winsock). To do this, you'll need to initialize Winsock, retrieve the list of available network interfaces, and then query each interface for its configured IP addresses.
Here's a basic example of how you could do this:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <stdlib.h>
#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "iphlpapi.lib")
int main() {
WSADATA wsaData;
DWORD dwSize = 0;
DWORD dwRetVal = 0;
// Initialize Winsock
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
// Get the size of the IP_ADAPTER_ADDRESSES struct
GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, NULL, &dwSize);
IP_ADAPTER_ADDRESSES* pAddresses = (IP_ADAPTER_ADDRESSES*)malloc(dwSize);
// Retrieve the adapter information
if ((dwRetVal = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, pAddresses, &dwSize)) == NO_ERROR) {
// Loop through the list of adapters
for (IP_ADAPTER_ADDRESSES* pCurrAddresses = pAddresses; pCurrAddresses != NULL; pCurrAddresses = pCurrAddresses->Next) {
printf("\nAdapter name: %s\n", pCurrAddresses->AdapterName);
// Loop through the list of unicast addresses for IPv4 and IPv6
for (IP_ADAPTER_UNICAST_ADDRESS* pUnicast = pCurrAddresses->FirstUnicastAddress; pUnicast != NULL; pUnicast = pUnicast->Next) {
char ipAddress[INET6_ADDRSTRLEN] = {0};
void* pAddr = NULL;
// Determine the family of the IP address
if (pUnicast->Address.lpSockaddr->sa_family == AF_INET) {
// It's an IPv4 address
pAddr = &((struct sockaddr_in*)pUnicast->Address.lpSockaddr)->sin_addr;
printf("IPv4 Address: ");
} else if (pUnicast->Address.lpSockaddr->sa_family == AF_INET6) {
// It's an IPv6 address
pAddr = &((struct sockaddr_in6*)pUnicast->Address.lpSockaddr)->sin6_addr;
printf("IPv6 Address: ");
}
// Convert the binary IP address to a string
if (pAddr) {
InetNtop(pUnicast->Address.lpSockaddr->sa_family, pAddr, ipAddress, sizeof(ipAddress));
printf("%s\n", ipAddress);
}
}
}
} else {
printf("GetAdaptersAddresses failed with error: %d\n", dwRetVal);
}
// Clean up
free(pAddresses);
WSACleanup();
return 0;
}
This code initializes Winsock, retrieves the network adapter information using GetAdaptersAddresses, and then iterates through the list of adapters and their unicast IP addresses. For each IP address, it determines whether it's an IPv4 or IPv6 address, and uses InetNtop to convert it to a human-readable string format before printing it out.
Don't forget to include the necessary libraries (Ws2_32.lib and iphlpapi.lib) as indicated by the #pragma comment directives.
Please note that this is a simple example and may require additional error handling and cleanup for robustness, depending on the needs of your application.