diff --git a/include/utils.h b/include/utils.h index 552042d..8dfecd0 100644 --- a/include/utils.h +++ b/include/utils.h @@ -152,6 +152,20 @@ namespace Tins { * \return The interface's name. */ std::string interface_from_ip(uint32_t ip); + + /** + * \brief Finds the gateway's IP address for the given IP + * address. + * + * \param ip The IP address for which the default gateway will + * be searched. + * \param gw_addr This parameter will contain the gateway's IP + * address in case it is found. + * + * \return bool indicating wether the lookup was successfull. + */ + bool gateway_from_ip(uint32_t ip, uint32_t &gw_addr) ; + /** \brief Convert 16 bit integer into network byte order. * diff --git a/src/utils.cpp b/src/utils.cpp index f52623c..e5cd733 100644 --- a/src/utils.cpp +++ b/src/utils.cpp @@ -241,6 +241,29 @@ string Tins::Utils::interface_from_ip(uint32_t ip) { return ""; } +bool Tins::Utils::gateway_from_ip(uint32_t ip, uint32_t &gw_addr) { + ifstream input("/proc/net/route"); + bool match(false); + string iface; + string destination, mask; + uint32_t destination_int, mask_int; + ip = Utils::net_to_host_l(ip); + skip_line(input); + while(!match) { + input >> iface >> destination; + for(unsigned i(0); i < 6; ++i) + input >> mask; + from_hex(destination, destination_int); + from_hex(mask, mask_int); + if((ip & mask_int) == destination_int) { + gw_addr = destination_int; + return true; + } + skip_line(input); + } + return false; +} + set Tins::Utils::network_interfaces() { InterfaceCollector collector; generic_iface_loop(collector);