Sigar使用之:取得网卡流量数据

在网络应用中,经常要对网卡的流量进行统计分析。

和网卡相关的统计数据主要有:网卡信息(ip地址、子网掩码、mac地址等)、网卡的吞吐量、流量等等。

当然了使用sigar也可以获得这些数据。

下面通过例子说明:


package lab.sigar;

import java.util.ArrayList;
import java.util.List;

import org.hyperic.sigar.NetInterfaceConfig;
import org.hyperic.sigar.NetInterfaceStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import com.thoughtworks.xstream.XStream;

/**
* 网卡信息、接口数据、流量
*
* 使用Sigar获得网卡信息
*
*/
public class NetInterfaceData {

private NetInterfaceConfig config;
private NetInterfaceStat stat;
private long rxbps;
private long txbps;

public NetInterfaceData() {}

public void populate(Sigar sigar, String name)
throws SigarException {

config = sigar.getNetInterfaceConfig(name);

try {

long start = System.currentTimeMillis();
NetInterfaceStat statStart = sigar.getNetInterfaceStat(name);
long rxBytesStart = statStart.getRxBytes();
long txBytesStart = statStart.getTxBytes();
Thread.sleep(1000);
long end = System.currentTimeMillis();
NetInterfaceStat statEnd = sigar.getNetInterfaceStat(name);
long rxBytesEnd = statEnd.getRxBytes();
long txBytesEnd = statEnd.getTxBytes();

rxbps = (rxBytesEnd - rxBytesStart)*8/(end-start)*1000;
txbps = (txBytesEnd - txBytesStart)*8/(end-start)*1000;
stat = sigar.getNetInterfaceStat(name);
} catch (SigarException e) {

} catch (Exception e) {

}
}

public static NetInterfaceData gather(Sigar sigar, String name)
throws SigarException {

NetInterfaceData data = new NetInterfaceData();
data.populate(sigar, name);
return data;
}

public NetInterfaceConfig getConfig() {
return config;
}

public NetInterfaceStat getStat() {
return stat;
}



public long getRxbps() {
return rxbps;
}

public long getTxbps() {
return txbps;
}

public static void main(String[] args) throws Exception {
Sigar sigar = new Sigar();
String[] netIfs = sigar.getNetInterfaceList();
List netIfList = new ArrayList();
for ( String name:netIfs ) {
NetInterfaceData netIfData1 = NetInterfaceData.gather(sigar, name);
netIfList.add(netIfData1);
}
XStream xstream = new XStream();
xstream.alias("NetInterfaceDatas", List.class);
xstream.alias("NetInterfaceData", NetInterfaceData.class);
System.out.println(xstream.toXML(netIfList));
}
}


用到的jar包可以在《Sigar使用之:取得系统内存的数据》中取得

[url=http://www.51.la/?1613417][img]http://img.users.51.la/1613417.asp[/img][/url]

你可能感兴趣的:(Sigar)