Skip to content

Instantly share code, notes, and snippets.

@ngrodzitski
Last active December 21, 2023 12:13
Show Gist options
  • Save ngrodzitski/fd2f6079deda857a945fea1004f8fca2 to your computer and use it in GitHub Desktop.
Save ngrodzitski/fd2f6079deda857a945fea1004f8fca2 to your computer and use it in GitHub Desktop.
Network interface to ip addr
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <ifaddrs.h>
//
// network_iface_to_addr()
//
/**
* @brief For a given network interface finds an ipv4 inet address.
*
* @return A ipv4 address of the network interface if found,
* otherwise return empty optional.
*/
[[nodiscard]] std::optional< asio_ns::ip::address >
network_iface_to_addr( std::string_view iface_name )
{
try
{
ifaddrs * ifap;
if( -1 == getifaddrs( &ifap ) )
{
return std::nullopt;
}
std::unique_ptr< ifaddrs, decltype( &freeifaddrs ) > ifap_ptr{
ifap, &freeifaddrs
};
for( auto * iface = ifap; iface != nullptr; iface = iface->ifa_next )
{
if( iface->ifa_addr && iface->ifa_addr->sa_family == AF_INET
&& iface->ifa_name == iface_name )
{
auto * sa = reinterpret_cast< sockaddr_in * >( iface->ifa_addr );
return asio_ns::ip::address_v4{ ntohl(sa->sin_addr.s_addr) };
}
}
}
catch( ... )
{
}
return std::nullopt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment