⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 netif.c

📁 linux/unix下c/s形式的资源监视,客户端负责搜集机器,再传送到服务端.
💻 C
字号:
/* * Collect information about network interface. * * Copyright (c) 2004, by:      Jian Shen *    All rights reserved.      Peking University, China *                             <shenjian@net.pku.edu.cn> * * This file may be used subject to the terms and conditions of the * GNU Library General Public License Version 2, or any later version * at your option, as published by the Free Software Foundation. * 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 Library General Public License for more details. * */#include "netif.h"#include <ctype.h>#include <stdio.h>#include <string.h>#include <unistd.h>#include <sys/socket.h>#include <sys/ioctl.h>#include <net/if.h>#include <netinet/in.h>#include <arpa/inet.h>static 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_if_addr(char* ifname, struct netif* newif){    struct ifreq ifr;    int fd;		fd = socket(AF_INET, SOCK_DGRAM, 0);	if(fd < 0) {		perror("socket");		return -1;	}	strcpy(ifr.ifr_name, ifname);	ifr.ifr_addr.sa_family = AF_INET;	if(ioctl(fd, SIOCGIFADDR, &ifr) == 0) {		strcpy(newif->name, ifname);		newif->ipaddr = ifr.ifr_addr;		strcpy(ifr.ifr_name, ifname);		if(ioctl(fd, SIOCGIFBRDADDR, &ifr) == 0) {			newif->broadaddr = ifr.ifr_broadaddr;		}else {			close(fd);			return -1;		}		close(fd);		return 0;	}else {		close(fd);		return -1;	}}int get_netif(){	FILE *fp;	char buf[512];	int num_of_netif = 0;	int i;	fp = fopen("/proc/net/dev", "r");	if(!fp) {		fprintf(stderr, "Failed to open /proc/net/dev");		return -1;	}    fgets(buf, sizeof(buf), fp);	/* eat line */    fgets(buf, sizeof(buf), fp);	i = 0;    while (fgets(buf, sizeof(buf), fp)) {		char *s, name[10];		s = get_name(name, buf);		if(s) {			if(strcmp(name, "lo") == 0)				continue;			struct netif newif;			if(get_if_addr(name, &newif) == 0) {				if_table[i] = newif;				i++;			}		}    }	num_of_netif = i;	fclose(fp);	return num_of_netif;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -