Network Usage Monitoring in Linux using Java

2019-08-28 06:43发布

问题:

I've got a Java based media server which streams content to both a webpage and an android device. It's set up so it can be used by multiple users and also talk with other servers and share media with them.

I'd like to be able to monitor the total network traffic (kb/s) via a service in my media server, so I can see it via my android device or webpage without having to look at my server.

Is there an easy way to get this information with Java? Some kind of linux resource file? I've looked at netstat and few others from googling and they don't seem to deliver me what I want in an obvious fashion. I just need the total traffic, I don't need to know who is talking to me.

Thanks for any help. :)

pps: I'm using the most recent release of OpenSUSE, but also have working versions on Fedora (most recent).

回答1:

You can read network statistics from /proc/net/dev -- see http://linuxdevcenter.com/pub/a/linux/2000/11/16/LinuxAdmin.html for details.

You'll see something like this:

Inter-|   Receive                                                |  Transmit
 face |bytes    packets errs drop fifo frame compressed multicast|bytes    packets errs drop fifo colls carrier compressed
    lo:    2504      30    0    0    0     0          0         0     2504      30    0    0    0     0       0          0
  eth0:33769785 2548318    0    0    0     0          0         0  4146854  215379    0    0    0     0       0          0
  eth1:       0       0    0    0    0     0          0         0        0       0    0    0    0     0       0          0

So you'll need to open the file, read each line and check the first column to find the interface(s) you care about, and then extract the received and/or sent bytes and/or packets. If you keep track of the time between reads, you can calculate the rate like this:

Let
b0 = bytes at time t0
b1 = bytes at time t1, some time later than t0.

Then you can calculate the rate, r, like this:
r = (b1 - b0) / (t1 - t0)