|
|
发表于 2005-11-1 15:42:48
|
显示全部楼层
对流量为0的网络接口有用,比如一般的lo;如果流量不是0,就得不到了,比如一般流量不为0的eth0,还有以下的这个(/proc/net/dev):
- Inter-| Receive | Transmit
- face |bytes packets errs drop fifo frame compressed multicast|bytes packets errs drop fifo colls carrier compressed
- lo: 1258287 30893 0 0 0 0 0 0 1258287 30893 0 0 0 0 0 0
- eth0:2584406784 25700762 1909 8 0 1909 0 0 442441 6369 0 0 0 0 0 0
- eth1:4288480977 81743660 0 0 0 0 0 0 1674397726 50377395 0 0 0 0 0 0
- sit0: 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
复制代码
试改如下,好像可以得到需要的结果:
- #include <stdio.h>
- #include <string.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <sys/ioctl.h>
- #include <net/if.h>
- #include <arpa/inet.h>
- int main()
- {
- int inet_sock;
- struct ifreq ifr;
- FILE *net_devs;
- char buf[1024];
- char interface[32];
- int index;
- net_devs = fopen("/proc/net/dev", "r");
- if(net_devs == NULL){
- perror("Can't open /proc/net/dev for reading");
- exit(1);
- }
- inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
- while(1){
- if(fscanf(net_devs, "%32s %1024[^\n]", interface, buf) <= 0){
- break;
- }
- index = 0;
- while ( index<32 && interface[index] != ':' ) {
- index++;
- }
- if (index>=32)
- continue;
- interface[index] = '\0';
- strcpy(ifr.ifr_name, interface);
- if (ioctl(inet_sock, SIOCGIFADDR, &ifr) < 0)
- perror("ioctl");
- printf("%s:\t%s\n", interface,
- inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr));
- }
- close(inet_sock);
- return 0;
- }
复制代码
对了,那个buf是做什么的?没有看出来。
Post by 小锁
- #include <string.h>
- #include <sys/socket.h>
- #include <sys/ioctl.h>
- #include <net/if.h>
- #include <stdio.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- int main()
- {
- int inet_sock;
- struct ifreq ifr;
- FILE *net_devs;
- char buf[1024];
- char interface[32];
- ...
- ...
- }
复制代码 |
|