Get all running non-loopback devices by default, thanks to Alexandre LAURENT!

This commit is contained in:
Arnout Engelen
2013-05-12 12:59:50 +00:00
parent f6220a3c0d
commit 7c599c8c80
3 changed files with 62 additions and 6 deletions

View File

@@ -19,11 +19,58 @@
*
*/
#include "devices.h"
device * determine_default_device()
#include <iostream>
#include <cstring>
#include <sys/socket.h>
#include <net/if.h>
#include <ifaddrs.h>
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;
}

View File

@@ -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

View File

@@ -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)){