#include "mnic.h"

static char *prase_digit(char **s)
{
        char *retp = NULL;
        char *p = *s;

        if(!p)return NULL;
	while(!isdigit(*p)){
		p++;
		if(*p == '\0')return NULL;
	}
        retp = p;
        while(isdigit(*p)){
                p++;
                if(*p == '\0'){
                        *s = NULL;
                        return retp;
                }
        }
        *p = '\0';
        p++;
        *s = p;
        return retp;
}


char *get_name(char *name, char *p)
{	
    while (isspace(*p))
	p++;
    while (*p) {
	if (isspace(*p))
	    break;
	if (*p == ':') {	/* could be an alias */
	    char *dot = p, *dotname = name;
	    *name++ = *p++;
	    while (isdigit(*p))
		*name++ = *p++;
	    if (*p != ':') {	/* it wasn't, backup */
		p = dot;
		name = dotname;
	    }
	    if (*p == '\0')
		return NULL;
	    p++;
	    break;
	}
	*name++ = *p++;
    }
    *name++ = '\0';
    return p;
}

int get_dev_fields(char *str, NETCARD_INFO *ife)
{
	int i = 0;
	char *retp[16];

	while((retp[i] = prase_digit(&str)) != NULL){i++;if(i > 15)break;}
	ife->rx_bytes = atoll(retp[0]);
	ife->rx_packets = atoll(retp[1]);
	ife->rx_errors = atol(retp[2]);
	ife->rx_dropped = atol(retp[3]);
	ife->rx_fifo_errors = atol(retp[4]);
	ife->rx_multicast = atol(retp[7]);
	ife->tx_bytes = atoll(retp[8]);
	ife->tx_packets = atoll(retp[9]);
	ife->tx_errors = atol(retp[10]);
	ife->tx_dropped = atol(retp[11]);
	ife->tx_fifo_errors = atol(retp[12]);
	ife->collisions = atol(retp[13]);
	ife->tx_carrier_errors = atol(retp[14]);
	return 0;
}

int if_fetch(NETCARD_INFO *ife)
{
	int skfd;
	struct ifreq ifr;

	if((skfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)return -1;

	strcpy(ifr.ifr_name, ife->charname);
	if (!ioctl(skfd, SIOCGIFFLAGS, &ifr))
		ife->flags = ifr.ifr_flags;

	if (!ioctl(skfd, SIOCGIFHWADDR, &ifr))
		ife->hwaddr = ifr.ifr_hwaddr;

	if (!ioctl(skfd, SIOCGIFMTU, &ifr))
		ife->mtu = ifr.ifr_mtu;

	if (!ioctl(skfd, SIOCGIFTXQLEN, &ifr))
		ife->tx_queue_len = ifr.ifr_qlen;

	if (!ioctl(skfd, SIOCGIFADDR, &ifr)) 
		ife->addr = ifr.ifr_addr;

	if (!ioctl(skfd, SIOCGIFBRDADDR, &ifr))
		ife->broadaddr = ifr.ifr_broadaddr;

	if (!ioctl(skfd, SIOCGIFNETMASK, &ifr))
		ife->netmask = ifr.ifr_netmask;

	ife->time_stamp = time(NULL);
	close(skfd);
	return 0;
}


int  ioc_get_name(NETCARD_INFO *name)
{
	int skfd;
	int ifrnum;
	int i = 0;
	struct ifconf ifc;
	struct ifreq buf[MAXNICNUM];

	if((skfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)return -1;
	memset(buf, 0, sizeof(buf));
	ifc.ifc_len = sizeof(buf);
       	ifc.ifc_buf = (caddr_t) buf;
	ioctl(skfd, SIOCGIFCONF, &ifc);
	ifrnum = ifc.ifc_len / sizeof(struct ifreq);
	while(ifrnum-- > 0){
		strcpy(name[i].charname, buf[ifrnum].ifr_name);
		i++;
	}
	close(skfd);
	return i;
}

