Created
December 16, 2017 13:39
-
-
Save AhnMo/b0d08ae02c10f291c445d643c5de1380 to your computer and use it in GitHub Desktop.
Get Internet connected Interface information - Visual C++
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
| #include <winsock2.h> | |
| #include <iphlpapi.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #pragma comment(lib, "IPHLPAPI.lib") | |
| #define MALLOC(x) HeapAlloc(GetProcessHeap(), 0, (x)) | |
| #define FREE(x) HeapFree(GetProcessHeap(), 0, (x)) | |
| int __cdecl main() { | |
| PIP_ADAPTER_INFO pAdapterInfo; | |
| PIP_ADAPTER_INFO pAdapter = NULL; | |
| DWORD dwRetVal = 0; | |
| UINT i; | |
| struct tm newtime; | |
| char buffer[32]; | |
| errno_t error; | |
| unsigned long ifIndex_; | |
| if (GetBestInterface(0, &ifIndex_) != NO_ERROR) { | |
| ifIndex_ = -1; | |
| } | |
| ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO); | |
| pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(sizeof(IP_ADAPTER_INFO)); | |
| if (pAdapterInfo == NULL) { | |
| return NULL; | |
| } | |
| if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) { | |
| FREE(pAdapterInfo); | |
| pAdapterInfo = (IP_ADAPTER_INFO *) MALLOC(ulOutBufLen); | |
| if (pAdapterInfo == NULL) { | |
| return NULL; | |
| } | |
| } | |
| ifIndex_ = -1; | |
| if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) { | |
| pAdapter = pAdapterInfo; | |
| while (pAdapter) { | |
| if ( | |
| (ifIndex_ == -1 && pAdapter->Type != MIB_IF_TYPE_ETHERNET) && // when no best interface and ethernet | |
| ifIndex_ != pAdapter->Index // when there is best interface | |
| ) { | |
| pAdapter = pAdapter->Next; | |
| continue; | |
| } | |
| printf("\tAdapter Name: \t%s\n", pAdapter->AdapterName); | |
| printf("\tAdapter Desc: \t%s\n", pAdapter->Description); | |
| printf("\tAdapter Addr: \t"); | |
| for (i = 0; i < pAdapter->AddressLength; i++) { | |
| if (i == (pAdapter->AddressLength - 1)) | |
| printf("%.2X\n", (int)pAdapter->Address[i]); | |
| else | |
| printf("%.2X-", (int)pAdapter->Address[i]); | |
| } | |
| 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); | |
| printf("\t***\n"); | |
| pAdapter = pAdapter->Next; | |
| printf("\n"); | |
| break; | |
| } | |
| } | |
| if (pAdapterInfo) | |
| FREE(pAdapterInfo); | |
| return 0; | |
| } | |
| // GetBestInterface | |
| // https://msdn.microsoft.com/ko-kr/library/windows/desktop/aa365920(v=vs.85).aspx | |
| // GetAdaptersInfo | |
| // https://msdn.microsoft.com/en-us/library/windows/desktop/aa365917(v=vs.85).aspx |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment