Skip to content

Instantly share code, notes, and snippets.

@mkamilov
Last active December 4, 2018 04:53
Show Gist options
  • Save mkamilov/5c548cdff73dac9c9e69cdedb8364cac to your computer and use it in GitHub Desktop.
Save mkamilov/5c548cdff73dac9c9e69cdedb8364cac to your computer and use it in GitHub Desktop.
get ipv6 address from Windows
#include <iostream>
#include <winsock2.h>
#include <iphlpapi.h>
#include <WS2tcpip.h>
#pragma comment(lib, "IPHLPAPI.lib")
#pragma comment(lib, "Ws2_32.lib")
using namespace std;
static char* ConvertLPWSTRToLPSTR(LPWSTR lpwszStrIn)
{
LPSTR pszOut = NULL;
if (lpwszStrIn != NULL)
{
int nInputStrLen = (int)wcslen(lpwszStrIn);
// Double NULL Termination
int nOutputStrLen = WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;
pszOut = new char[nOutputStrLen];
if (pszOut)
{
memset(pszOut, 0x00, nOutputStrLen);
WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut, nOutputStrLen, 0, 0);
}
}
return pszOut;
}
std::string GetIpv6TemporaryAddress()
{
IP_ADAPTER_ADDRESSES *adapterAddr;
DWORD dwSize = 0;
DWORD flags = GAA_FLAG_INCLUDE_PREFIX | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER;
DWORD dwRet = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, NULL, &dwSize);
if (dwRet == ERROR_BUFFER_OVERFLOW) {
adapterAddr = (IP_ADAPTER_ADDRESSES *)LocalAlloc(LMEM_ZEROINIT, dwSize);
if (adapterAddr == NULL) {
cout << "Can't query for adapter addresses - LocalAlloc error" << endl;
}
dwRet = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapterAddr, &dwSize);
if (dwRet != ERROR_SUCCESS) {
LocalFree(adapterAddr);
cout << "Can't query for adapter addresses - GetAdapterAddresses" << endl;;
}
else {
IP_ADAPTER_ADDRESSES *AI;
int i;
for (i = 0, AI = adapterAddr; AI != NULL; AI = AI->Next, i++) {
if (AI->FirstUnicastAddress != NULL) {
LPSTR strAdapterFriendlyName = ConvertLPWSTRToLPSTR(AI->FriendlyName);
string adapterFriendlyName(strAdapterFriendlyName);
delete[] strAdapterFriendlyName;
cout << "Adapter name : " << AI->AdapterName << endl;;
cout << "Adapter friendly name : " << adapterFriendlyName.c_str() << endl;
int count = 0;
for (PIP_ADAPTER_UNICAST_ADDRESS unicast = AI->FirstUnicastAddress; unicast; unicast = unicast->Next) {
struct sockaddr &addr = *unicast->Address.lpSockaddr;
const struct sockaddr_in6* addr6 = reinterpret_cast<const sockaddr_in6*>(&addr);
char ipv6Addr[262];
memset(ipv6Addr, '\0', 262);
inet_ntop(AF_INET6, &addr6->sin6_addr, ipv6Addr, 262);
string strIpAddr(ipv6Addr);
cout << "Found IPV6 : " << strIpAddr.c_str() << endl;
if (unicast->SuffixOrigin == IpSuffixOriginRandom) {
cout << "This is temporary address!" << endl;
return strIpAddr;
}
}
}
}
LocalFree(adapterAddr);
}
}
return "";
}
int main(int argc, const char * argv[]) {
GetIpv6TemporaryAddress();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment