在Linux中,netstat
是一个经典的网络工具,用于显示网络连接、路由表、接口统计等信息。虽然 netstat
本身不直接提供流量统计功能,但可以通过结合其他工具或选项来间接实现流量统计。以下是几种常见的方法:
netstat -i
查看接口流量统计netstat -i
Kernel Interface table
Iface MTU RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg
eth0 1500 1234567 0 0 0 987654 0 0 0 BMRU
lo 65536 789012 0 0 0 789012 0 0 0 LRU
RX-OK
:接收的数据包总数。TX-OK
:发送的数据包总数。RX-ERR/TX-ERR
:错误数据包数。watch
动态监控流量watch -n 1 "netstat -i"
RX-OK/TX-OK
的变化来计算流量速率(包/秒)。netstat -s
查看协议级统计netstat -s
Tcp:
1234567 active connections openings
987654 passive connection openings
123456 segments received
789012 segments sent out
netstat
的流量统计功能有限,建议使用以下工具替代:
ip -s link
(推荐)ip -s link show eth0
bytes
和数据包数 packets
)。ifconfig
ifconfig eth0
RX bytes
和 TX bytes
(已接收/发送的总字节数)。nload
/ iftop
/ bmon
bash
nload eth0 # 实时显示带宽使用情况(需安装)
iftop -i eth0 # 按连接显示流量(需安装)
vnstat
(长期流量统计)vnstat -l # 实时监控
vnstat -d # 每日统计
通过记录两次 netstat -i
或 ifconfig
的输出差值计算流量:
# 第一次记录
RX1=$(netstat -i | grep eth0 | awk '{print $3}')
TX1=$(netstat -i | grep eth0 | awk '{print $7}')
sleep 10
# 第二次记录
RX2=$(netstat -i | grep eth0 | awk '{print $3}')
TX2=$(netstat -i | grep eth0 | awk '{print $7}')
# 计算10秒内的流量(包数)
echo "RX packets: $((RX2 - RX1)), TX packets: $((TX2 - TX1))"
netstat -i
或 ifconfig
查看接口的总数据包/字节数。nload
、iftop
或 ip -s link
。vnstat
。⚠️ 注意:
netstat
已逐渐被ss
和ip
命令取代(如ss -s
可查看套接字统计),建议在新系统中优先使用iproute2
工具集。