用Sigar取得网卡流量数据
程序员文章站
2022-06-05 18:46:53
...
在网络应用中,经常要对网卡的流量进行统计分析。
和网卡相关的统计数据主要有:网卡信息(ip地址、子网掩码、mac地址等)、网卡的吞吐量、流量等等。
当然了使用sigar也可以获得这些数据。
下面通过例子说明:
1.package lab.sigar;
2.
3.import java.util.ArrayList;
4.import java.util.List;
5.
6.import org.hyperic.sigar.NetInterfaceConfig;
7.import org.hyperic.sigar.NetInterfaceStat;
8.import org.hyperic.sigar.Sigar;
9.import org.hyperic.sigar.SigarException;
10.
11.import com.thoughtworks.xstream.XStream;
12.
13./**
14. * 网卡信息、接口数据、流量
15. *
16. * 使用Sigar获得网卡信息
17. *
18. */
19.public class NetInterfaceData {
20.
21. private NetInterfaceConfig config;
22. private NetInterfaceStat stat;
23. private long rxbps;
24. private long txbps;
25.
26. public NetInterfaceData() {}
27.
28. public void populate(Sigar sigar, String name)
29. throws SigarException {
30.
31. config = sigar.getNetInterfaceConfig(name);
32.
33. try {
34.
35. long start = System.currentTimeMillis();
36. NetInterfaceStat statStart = sigar.getNetInterfaceStat(name);
37. long rxBytesStart = statStart.getRxBytes();
38. long txBytesStart = statStart.getTxBytes();
39. Thread.sleep(1000);
40. long end = System.currentTimeMillis();
41. NetInterfaceStat statEnd = sigar.getNetInterfaceStat(name);
42. long rxBytesEnd = statEnd.getRxBytes();
43. long txBytesEnd = statEnd.getTxBytes();
44.
45. rxbps = (rxBytesEnd - rxBytesStart)*8/(end-start)*1000;
46. txbps = (txBytesEnd - txBytesStart)*8/(end-start)*1000;
47. stat = sigar.getNetInterfaceStat(name);
48. } catch (SigarException e) {
49.
50. } catch (Exception e) {
51.
52. }
53. }
54.
55. public static NetInterfaceData gather(Sigar sigar, String name)
56. throws SigarException {
57.
58. NetInterfaceData data = new NetInterfaceData();
59. data.populate(sigar, name);
60. return data;
61. }
62.
63. public NetInterfaceConfig getConfig() {
64. return config;
65. }
66.
67. public NetInterfaceStat getStat() {
68. return stat;
69. }
70.
71.
72.
73. public long getRxbps() {
74. return rxbps;
75. }
76.
77. public long getTxbps() {
78. return txbps;
79. }
80.
81. public static void main(String[] args) throws Exception {
82. Sigar sigar = new Sigar();
83. String[] netIfs = sigar.getNetInterfaceList();
84. List netIfList = new ArrayList();
85. for ( String name:netIfs ) {
86. NetInterfaceData netIfData1 = NetInterfaceData.gather(sigar, name);
87. netIfList.add(netIfData1);
88. }
89. XStream xstream = new XStream();
90. xstream.alias("NetInterfaceDatas", List.class);
91. xstream.alias("NetInterfaceData", NetInterfaceData.class);
92. System.out.println(xstream.toXML(netIfList));
93. }
94.}
上一篇: 这是一个静态页面爬虫学习