Skip to content

Instantly share code, notes, and snippets.

@Nihlus
Created September 14, 2018 09:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nihlus/db1e48856133fad82a4dcfddba5c3796 to your computer and use it in GitHub Desktop.
Save Nihlus/db1e48856133fad82a4dcfddba5c3796 to your computer and use it in GitHub Desktop.
// Find the IP address we're on, given a configured interface
const string interface = "enx847beb51d7b4";
ifaddrs* adresses { };
getifaddrs(&adresses);
while (adresses->ifa_name != interface)
{
if (adresses->ifa_next == nullptr)
{
return -3;
}
adresses = adresses->ifa_next;
}
string address;
// Grab the address
if (adresses->ifa_addr->sa_family == AF_INET)
{
auto addressPtr = &((sockaddr_in*)adresses->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 (adresses->ifa_addr->sa_family == AF_INET6)
{
auto addressPtr = &((sockaddr_in6*)adresses->ifa_addr)->sin6_addr;
auto nameBuffer = make_unique<char[]>(INET6_ADDRSTRLEN);
inet_ntop(AF_INET6, addressPtr, nameBuffer.get(), INET6_ADDRSTRLEN);
address = string(nameBuffer.get());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment