问题
I want to get network bandwidth usage for each process. I have found a lot of information about this, such as iftop, nethogs, linux process explorer... But all of them get process brandwidth usage by capture packet(libpcap), by my test in linux it consume a lot of cpu(%10-%15) and the speed of flow is 11MByte/s. If I can get flow rate for each port I can solve this questions because I hava get the table about process port used. So I want to know is there any other way to get port flow without capture packet.
回答1:
As far as I know Linux doesn't offer an alternative interface to pcap for calculating network usage. /proc/<PID>/stat(us)
contains various process information but nothing about network access, only the total I/O usage including disk access.
Similarly, to know the port you have to read at least the IP header. Hence I assume it is not possible to speed this up significantly, because analyzing all packets in user space will always be slow. A kernel module for this task seems to be the only option.
回答2:
/proc/[pid]/net/netstat
contains the bandwidth information per process,where pid is the process id.
cat /proc/"pid"/net/netstat | \
awk '(f==0) {name=$1; i=2; while ( i<=NF) {n[i] = $i; i++ }; f=1; next} \
(f==1){ i=2; while ( i<=NF){ printf "%s%s = %d\n", name, n[i], $i; i++}; f=0} '
Reference: https://sa-chernomor.livejournal.com/9858.html
来源:https://stackoverflow.com/questions/22219550/how-to-get-process-or-port-network-bandwidth-usage-in-linux