diff --git a/devices.cpp b/devices.cpp index db52532..09b76bd 100644 --- a/devices.cpp +++ b/devices.cpp @@ -19,11 +19,58 @@ * */ - #include "devices.h" -device * determine_default_device() +#include +#include + +#include +#include +#include + +device * get_default_devices() { - return new device("eth0"); + struct ifaddrs *ifaddr, *ifa; + + if (getifaddrs(&ifaddr) == -1) + { + std::cerr << "Fail to get interface addresses" << std::endl; + // perror("getifaddrs"); + return NULL; + } + + device* devices = NULL; + for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) + { + if (ifa->ifa_addr == NULL) + continue; + + // The interface is up, not a loopback and running ? + if ( !(ifa->ifa_flags & IFF_LOOPBACK) && + (ifa->ifa_flags & IFF_UP) && + (ifa->ifa_flags & IFF_RUNNING) ) + { + // Check if the interface is already known by going through all the devices + bool found = false; + device* pIter = devices; + while(pIter != NULL) + { + if ( strcmp(ifa->ifa_name,pIter->name) == 0 ) + { + found = true; + } + pIter = pIter->next; + } + + // We found a new interface, let's add it + if ( found == false ) + { + devices = new device(strdup(ifa->ifa_name),devices); + } + } + } + + freeifaddrs(ifaddr); + return devices; } diff --git a/devices.h b/devices.h index 6652305..5642ede 100644 --- a/devices.h +++ b/devices.h @@ -34,6 +34,10 @@ public: device * next; }; -device * determine_default_device(); +/** + * This function can return null, if no good interface is found + * The function avoids loopback interface and down/not running interfaces + */ +device * get_default_devices(); #endif diff --git a/main.cpp b/main.cpp index 0fa74bb..8f05feb 100644 --- a/main.cpp +++ b/main.cpp @@ -18,7 +18,7 @@ static void help(void) //std::cerr << " -f : format of packets on interface, default is eth.\n"; std::cerr << " -p : sniff in promiscious mode (not recommended).\n"; std::cerr << " -s : sort output by sent column.\n"; - std::cerr << " device : device(s) to monitor. default is eth0\n"; + std::cerr << " device : device(s) to monitor. default is all interfaces up and running excluding loopback\n"; std::cerr << std::endl; std::cerr << "When nethogs is running, press:\n"; std::cerr << " q: quit\n"; @@ -88,7 +88,12 @@ int main (int argc, char** argv) if (devices == NULL) { - devices = determine_default_device(); + devices = get_default_devices(); + if ( devices == NULL ) + { + std::cerr << "Not devices to monitor" << std::endl; + return 0; + } } if ((!tracemode) && (!DEBUG)){