Annotation of embedaddon/miniupnpd/linux/getifstats.c, revision 1.1
1.1 ! misho 1: /* $Id: getifstats.c,v 1.7 2010/02/15 10:11:34 nanard Exp $ */
! 2: /* MiniUPnP project
! 3: * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/
! 4: * (c) 2006,2007 Thomas Bernard
! 5: * This software is subject to the conditions detailed
! 6: * in the LICENCE file provided within the distribution */
! 7:
! 8: #include <stdio.h>
! 9: #include <stdlib.h>
! 10: #include <syslog.h>
! 11: #include <string.h>
! 12: #include <time.h>
! 13:
! 14: #include "../getifstats.h"
! 15: #include "../config.h"
! 16:
! 17: int
! 18: getifstats(const char * ifname, struct ifdata * data)
! 19: {
! 20: FILE *f;
! 21: char line[512];
! 22: char * p;
! 23: int i;
! 24: int r = -1;
! 25: #ifdef ENABLE_GETIFSTATS_CACHING
! 26: static time_t cache_timestamp = 0;
! 27: static struct ifdata cache_data;
! 28: time_t current_time;
! 29: #endif
! 30: if(!data)
! 31: return -1;
! 32: data->baudrate = 4200000;
! 33: data->opackets = 0;
! 34: data->ipackets = 0;
! 35: data->obytes = 0;
! 36: data->ibytes = 0;
! 37: if(!ifname || ifname[0]=='\0')
! 38: return -1;
! 39: #ifdef ENABLE_GETIFSTATS_CACHING
! 40: current_time = time(NULL);
! 41: if(current_time == ((time_t)-1)) {
! 42: syslog(LOG_ERR, "getifstats() : time() error : %m");
! 43: } else {
! 44: if(current_time < cache_timestamp + GETIFSTATS_CACHING_DURATION) {
! 45: memcpy(data, &cache_data, sizeof(struct ifdata));
! 46: return 0;
! 47: }
! 48: }
! 49: #endif
! 50: f = fopen("/proc/net/dev", "r");
! 51: if(!f) {
! 52: syslog(LOG_ERR, "getifstats() : cannot open /proc/net/dev : %m");
! 53: return -1;
! 54: }
! 55: /* discard the two header lines */
! 56: if(!fgets(line, sizeof(line), f) || !fgets(line, sizeof(line), f)) {
! 57: syslog(LOG_ERR, "getifstats() : error reading /proc/net/dev : %m");
! 58: }
! 59: while(fgets(line, sizeof(line), f)) {
! 60: p = line;
! 61: while(*p==' ') p++;
! 62: i = 0;
! 63: while(ifname[i] == *p) {
! 64: p++; i++;
! 65: }
! 66: /* TODO : how to handle aliases ? */
! 67: if(ifname[i] || *p != ':')
! 68: continue;
! 69: p++;
! 70: while(*p==' ') p++;
! 71: data->ibytes = strtoul(p, &p, 0);
! 72: while(*p==' ') p++;
! 73: data->ipackets = strtoul(p, &p, 0);
! 74: /* skip 6 columns */
! 75: for(i=6; i>0 && *p!='\0'; i--) {
! 76: while(*p==' ') p++;
! 77: while(*p!=' ' && *p) p++;
! 78: }
! 79: while(*p==' ') p++;
! 80: data->obytes = strtoul(p, &p, 0);
! 81: while(*p==' ') p++;
! 82: data->opackets = strtoul(p, &p, 0);
! 83: r = 0;
! 84: break;
! 85: }
! 86: fclose(f);
! 87: #ifdef ENABLE_GETIFSTATS_CACHING
! 88: if(r==0 && current_time!=((time_t)-1)) {
! 89: cache_timestamp = current_time;
! 90: memcpy(&cache_data, data, sizeof(struct ifdata));
! 91: }
! 92: #endif
! 93: return r;
! 94: }
! 95:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>