Que sabes de GNU/Linux?

miércoles, 1 de abril de 2009

Lector de estatus de interfaces en Linux.c

#include
#include
#include
#include
typedef unsigned long long ull

int parseDevFile(const char * iface, ull *bRx, ull *pRx,
ull *bTx, ull *pTx)
{
FILE * fp = NULL;
char * line = NULL;
unsigned int len = 0;
fp = fopen("/proc/net/dev", "r");
if(fp==NULL)
{
return -1;
}
while(getline(&line,&len,fp)!= -1)
{
if(strstr(line,iface)!=NULL){
sscanf(strstr(line,":")+1,"%llu%llu%*u%*u%*u%*u%*u%*u%llu%llu",bRx, pRx, bTx, pTx);
}
}
fclose(fp);
free(line);
return 0;
}

void dumpInterfaceUsage(const char * iface)
{
ull ifaceBRxOld=0,ifaceBTxOld=0,ifacePRxOld=0,ifacePTxOld=0;
ull ifaceBRxNew=0,ifaceBTxNew=0,ifacePRxNew=0,ifacePTxNew=0;
const int SLEEP_TIME = 2;

if(parseDevFile(iface,&ifaceBRxOld,&ifacePRxOld,&ifaceBTxOld,&ifacePTxOld)==-1) return;
sleep(SLEEP_TIME);
while(1)
{
if(parseDevFile(iface,&ifaceBRxNew,&ifacePRxNew,&ifaceBTxNew,&ifacePTxNew)==-1) return;
printf("%s In: %8.2f kbyte/s %5llu P/s Out: %8.2f kbyte/s%5llu P/s\n", iface,
(ifaceBRxNew-ifaceBRxOld)/(SLEEP_TIME * 1024.0),
(ifacePRxNew-ifacePRxOld)/SLEEP_TIME,
(ifaceBTxNew-ifaceBTxOld)/(SLEEP_TIME * 1024.0),
(ifacePTxNew-ifacePTxOld)/SLEEP_TIME);
ifaceBRxOld=ifaceBRxNew;
ifaceBTxOld=ifaceBTxNew;
ifacePRxOld=ifacePRxNew;
ifacePTxOld=ifacePTxNew;
sleep(SLEEP_TIME);
}
}

int main(int argc, char **argv)
{
if(argc != 2)
{
printf("Usage: %s interfacename\n", argv[0]);
exit(1);
}
dumpInterfaceUsage(argv[1]);
return 0;
}