Skip to content

Instantly share code, notes, and snippets.

@maldevel
Last active October 31, 2018 06:46
Show Gist options
  • Save maldevel/f1c3fe0601b2c59cba28715b12b07132 to your computer and use it in GitHub Desktop.
Save maldevel/f1c3fe0601b2c59cba28715b12b07132 to your computer and use it in GitHub Desktop.
Dexter retrieve active network interface IP address snippet
//https://github.com/twelvesec/dexter
//GNU General Public License v3.0
//@maldevel
//...
std::string libsysteminfo::get_active_netface_ip(void) {
std::string ipaddress = "";
DWORD size = 0;
ULONG result = 0;
PIP_ADAPTER_ADDRESSES aAddr = NULL;
PIP_ADAPTER_ADDRESSES aAddrIndex = NULL;
PIP_ADAPTER_UNICAST_ADDRESS aAddrUnicast = NULL;
WSADATA wsaData;
WCHAR *buf;
unsigned long bufSize = 50; //xxx.xxx.xxx.xxx
if ((result = GetAdaptersAddresses(0, 0, 0, 0, &size)) != ERROR_BUFFER_OVERFLOW) {
return "";
}
if ((aAddr = (PIP_ADAPTER_ADDRESSES)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, size)) == NULL) {
return "";
}
if (GetAdaptersAddresses(AF_INET, GAA_FLAG_INCLUDE_PREFIX, 0, aAddr, &size) != NO_ERROR) {
HeapFree(GetProcessHeap(), 0, aAddr);
aAddr = NULL;
return "";
}
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
HeapFree(GetProcessHeap(), 0, aAddr);
aAddr = NULL;
return "";
}
aAddrIndex = aAddr;
std::wstring tmp;
while (aAddrIndex) {
if ((aAddrIndex->IfType == 6 || aAddrIndex->IfType == 71) && aAddrIndex->OperStatus == 1 &&
std::wstring(aAddrIndex->Description).find(L"Hyper-V") == std::string::npos &&
std::wstring(aAddrIndex->Description).find(L"VirtualBox") == std::string::npos &&
std::wstring(aAddrIndex->Description).find(L"VMware") == std::string::npos) {
if ((aAddrUnicast = aAddrIndex->FirstUnicastAddress) != NULL) {
if ((buf = (WCHAR*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, bufSize * sizeof(WCHAR))) == NULL) {
continue;
}
if (WSAAddressToStringW(aAddrUnicast->Address.lpSockaddr,
aAddrUnicast->Address.iSockaddrLength, NULL, buf, &bufSize) == 0) {
tmp += std::wstring(buf) + L" ";
HeapFree(GetProcessHeap(), 0, buf);
buf = NULL;
}
}
}
aAddrIndex = aAddrIndex->Next;
}
HeapFree(GetProcessHeap(), 0, aAddr);
aAddr = NULL;
WSACleanup();
tmp = tmp.substr(0, tmp.size() - 1);
ipaddress = std::string(tmp.begin(), tmp.end());
return ipaddress;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment