您的位置:首页 > 运维架构 > Linux

Linux下简单限制网卡的带宽

2009-08-23 15:17 453 查看
[文章作者:张宴 本文版本:v1.0 最后修改:2008.11.20 转载请注明原文链接:http://blog.s135.com/post/380/]

  Linux下限制网卡的带宽,可用来模拟服务器带宽耗尽,从而测试服务器在此时的访问效果。

  1、安装iproute

yum -y install iproute

  2、限制eth0网卡的带宽为50kbit:

/sbin/tc qdisc add dev eth0 root tbf rate 50kbit latency 50ms burst 1000

  3、限制带宽为50kbit后,在百兆局域网中wget下载一个大文件:

[root@localhost ~]# wget http://192.168.1.7/test.zip
--19:40:27-- http://192.168.1.7/test.zip
Connecting to 192.168.1.7:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 23862312 (23M) [application/zip]
Saving to: `test.zip'

37% [=======> ] 8,994,816 457K/s eta 27s

  下载速度为457K/s,限制效果达到。

  4、解除eth0网卡的带宽限制:

/sbin/tc qdisc del dev eth0 root tbf

  5、对比:未作带宽限制情况下,在百兆局域网中wget下载一个大文件:

[root@localhost ~]# wget http://192.168.1.7/test.zip
--19:44:33-- http://192.168.1.7/test.zip
Connecting to 192.168.1.7:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 23862312 (23M) [application/zip]
Saving to: `test.zip'

100%[==========>] 23,862,312 6.14M/s in 3.7s

19:44:36 (6.16 MB/s) - `test.zip' saved [23862312/23862312]

  下载速度为6.16MB/s。

今天自己写的一个程序,想看看music.njupt.edu.cn的带宽占用情况.
原理非常简单,程序写的比较笨,但是应该可以读懂.
呵呵,要是喜欢可以转载这个程序,但拜托不要修改这篇文章.

大家多多指点啦,如果有更好的实现方法告诉我哦:)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>

void count()
{
FILE *fp;
char buf[256],interface[16];
char *tmp,*next;
long unsigned RxBytes,TxBytes,None;
double RxBPS,TxBPS,TotalBPS;
static long unsigned LastRxBytes[10],LastTxBytes[10];
int i;

system("clear");
fp=fopen("/proc/net/dev","r");
for (i=0;i<=1;i++)
fgets(buf,255,fp);
for (i=0;fgets(buf,255,fp)!=NULL;i++)
{
TxBPS=RxBPS=TotalBPS=0;
tmp=strchr(buf,':');
next=tmp+1;
tmp[0]='/0';
strcpy(interface,buf);
strcpy(buf,next);
sscanf(buf,
"%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu/n",
&RxBytes,&None,&None,&None,&None,&None,&None,&None,&TxBytes,&None,
&None,&None,&None,&None,&None,&None);
if (LastRxBytes[i]!=0 && LastRxBytes[i]<RxBytes)
{
RxBPS=(RxBytes-LastRxBytes[i])*8;
}
if (LastTxBytes[i]!=0 && LastTxBytes[i]<TxBytes)
{
TxBPS=(TxBytes-LastTxBytes[i])*8;
}
TotalBPS=RxBPS+TxBPS;
printf("Interface:%s/n"
"Rx:%.0f BPS %.3f MBPS/n"
"Tx:%.0f BPS %.3f MBPS/n"
"Total:%.0f BPS %.3f MBPS/n/n",
interface,RxBPS,RxBPS/1024/1024,TxBPS,TxBPS/1024/1024,
TotalBPS,TotalBPS/1024/1024);
LastRxBytes[i]=RxBytes;
LastTxBytes[i]=TxBytes;
}
fclose(fp);
signal(SIGALRM,count);
alarm(1);
}

int main(void)
{
count();
for(;;);
exit(0);
}

--
如果你看见我累了,请给我一杯水;如果你发现你爱上了我,请给我一个吻!

LINUX实时查看带宽

官方站点:http://people.suug.ch/~tgr/bmon/
gentoo:
安装:emerge net-analyzer/bmon

基本用法:bmon -o ascii -p eth0

其它linux系统可参照官方站点的说明使用。

带宽统计vnstat
官方站点:http://humdi.net/vnstat/
gentoo:
安装:emerge vnstat
第一次使用需要对每个网卡运行:#vnstat -u -i eth0 ……
1、查看5秒内网卡eth0的平均流量:
#vnstat -tr -i eth0
2、网卡eth0一周内的流量:
#vnstat -i eth0 -w
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: