Created
September 14, 2018 11:01
-
-
Save Nihlus/ad1246c1dccf32ceeb54694a02908370 to your computer and use it in GitHub Desktop.
This file contains 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
string GetLocalNetworkAddress() | |
{ | |
// Find the IP address we're on, given a configured interface | |
const string interface = "enx847beb51d7b4"; | |
ifaddrs* adresses { }; | |
getifaddrs(&adresses); | |
ifaddrs* currentAddress = adresses; | |
while (currentAddress->ifa_next != nullptr) | |
{ | |
bool isIPv4 = currentAddress->ifa_addr->sa_family == AF_INET; | |
bool isIPv6 = currentAddress->ifa_addr->sa_family == AF_INET6; | |
if (currentAddress->ifa_name == interface && (isIPv4 | isIPv6)) | |
{ | |
break; | |
} | |
currentAddress = currentAddress->ifa_next; | |
} | |
string address; | |
// Grab the address | |
if (currentAddress->ifa_addr->sa_family == AF_INET) | |
{ | |
auto addressPtr = &((sockaddr_in*)currentAddress->ifa_addr)->sin_addr; | |
auto nameBuffer = make_unique<char[]>(INET_ADDRSTRLEN); | |
inet_ntop(AF_INET, addressPtr, nameBuffer.get(), INET_ADDRSTRLEN); | |
address = string(nameBuffer.get()); | |
} | |
else if (currentAddress->ifa_addr->sa_family == AF_INET6) | |
{ | |
auto addressPtr = &((sockaddr_in6*)currentAddress->ifa_addr)->sin6_addr; | |
auto nameBuffer = make_unique<char[]>(INET6_ADDRSTRLEN); | |
inet_ntop(AF_INET6, addressPtr, nameBuffer.get(), INET6_ADDRSTRLEN); | |
address = string(nameBuffer.get()); | |
} | |
freeifaddrs(adresses); | |
return address; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment