/*
 *  Authors: pbrufal (and tican)
 *
 *  Declarations for Syscriptor.
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <arpa/inet.h>
#include <net/if.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <unistd.h>

void network(const int BUF_SIZE, const int BUF_SIZE5)
{
	struct ifconf ifc;
	struct ifreq *ifr=NULL;
	struct utsname name;
	FILE *file;
	int fd, i, n, total;
	char buf[BUF_SIZE], buf2[BUF_SIZE5];
	char *card, *card2, *card3, *fname, *iname, *myip, *mynetmask;

	fname = "/proc/pci";
	file = fopen(fname, "r");
	if ( !file ) {
		fprintf(stderr, "Could not open %s. Bailing out.\n", fname);
		return;
	}

	puts("");
	printf("  NETWORK\n\n");

	printf("  Ethernet adapter(s):\n");

	while ( fgets(buf, BUF_SIZE, file) ) {
		card = strstr(buf,"Ethernet");
		if ( card ) {
			card2 = strchr(card, '(');
			if ( card2 ) {
				card2[-1] = 0;
				card3 = strchr(card,':')+1;
				printf(" %s\n", card3);
			}
		}
	}
	fclose(file);

	puts("");

	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
		return;
	}
	ifc.ifc_len = BUF_SIZE;
	ifc.ifc_buf = buf2;
	if (ioctl(fd, SIOCGIFCONF, &ifc) != 0) {
		close(fd);
		return;
	} 
	ifr = ifc.ifc_req;
	n = ifc.ifc_len / sizeof(struct ifreq);

	printf("  Interfaces:\n");

	total = 0;
	for (i=n-1; i>=0 && total < 8; i--) {
		if ( ioctl(fd, SIOCGIFADDR, &ifr[i]) != 0 ) {
			continue;
		}
		iname = ifr[i].ifr_name;
		printf("\n  %s:\n",iname);
		myip = inet_ntoa( ((struct sockaddr_in *)&ifr[i].ifr_addr)->sin_addr );
		printf("\tIP:\t\t%s\n",myip);
		if ( ioctl(fd, SIOCGIFFLAGS, &ifr[i]) != 0 ) {
			continue;
		}
		if ( !(ifr[i].ifr_flags & IFF_UP) ) {
			continue;
		}
		if ( ioctl(fd, SIOCGIFNETMASK, &ifr[i]) != 0 ) {
			continue;
		}
 		mynetmask = inet_ntoa(((struct sockaddr_in *)&ifr[i].ifr_addr)->sin_addr);
		printf("\tNetmask:\t%s\n",mynetmask);
		total++;
	}
	close(fd);

	puts("");

	if (uname(&name) != -1) {
		printf("  Hostname:\n");
		printf("  %s\n", name.nodename);
	} else {
		fprintf(stderr, "  Could not find your hostname\n");
		return;
	}

	puts("");
}
