-
-
Save ashumkin/77e5cfc771b075158d51d88871db1a6a to your computer and use it in GitHub Desktop.
GetAdaptersAddresses() sample code...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #ifndef _WIN32_WINNT | |
| #define _WIN32_WINNT 0x0600 | |
| #endif | |
| #include <stdio.h> | |
| #include <winsock2.h> | |
| #include <iphlpapi.h> | |
| #include <ws2tcpip.h> | |
| #pragma comment(lib, "ws2_32.lib") | |
| #pragma comment(lib, "iphlpapi.lib") | |
| void print_adapter(PIP_ADAPTER_ADDRESSES aa) | |
| { | |
| char buf[BUFSIZ]; | |
| memset(buf, 0, BUFSIZ); | |
| WideCharToMultiByte(CP_ACP, 0, aa->FriendlyName, wcslen(aa->FriendlyName), buf, BUFSIZ, NULL, NULL); | |
| printf("adapter_name:%s\n", buf); | |
| } | |
| void print_addr(PIP_ADAPTER_UNICAST_ADDRESS ua) | |
| { | |
| char buf[BUFSIZ]; | |
| int family = ua->Address.lpSockaddr->sa_family; | |
| printf("\t%s ", family == AF_INET ? "IPv4":"IPv6"); | |
| memset(buf, 0, BUFSIZ); | |
| getnameinfo(ua->Address.lpSockaddr, ua->Address.iSockaddrLength, buf, sizeof(buf), NULL, 0,NI_NUMERICHOST); | |
| printf("%s\n", buf); | |
| } | |
| bool print_ipaddress() | |
| { | |
| DWORD rv, size; | |
| PIP_ADAPTER_ADDRESSES adapter_addresses, aa; | |
| PIP_ADAPTER_UNICAST_ADDRESS ua; | |
| rv = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, NULL, &size); | |
| if (rv != ERROR_BUFFER_OVERFLOW) { | |
| fprintf(stderr, "GetAdaptersAddresses() failed..."); | |
| return false; | |
| } | |
| adapter_addresses = (PIP_ADAPTER_ADDRESSES)malloc(size); | |
| rv = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_INCLUDE_PREFIX, NULL, adapter_addresses, &size); | |
| if (rv != ERROR_SUCCESS) { | |
| fprintf(stderr, "GetAdaptersAddresses() failed..."); | |
| free(adapter_addresses); | |
| return false; | |
| } | |
| for (aa = adapter_addresses; aa != NULL; aa = aa->Next) { | |
| print_adapter(aa); | |
| for (ua = aa->FirstUnicastAddress; ua != NULL; ua = ua->Next) { | |
| print_addr(ua); | |
| } | |
| } | |
| free(adapter_addresses); | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| WSAData d; | |
| if (WSAStartup(MAKEWORD(2, 2), &d) != 0) { | |
| return -1; | |
| } | |
| print_ipaddress(); | |
| WSACleanup(); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment