Linux netstat -su 命令从哪里获取统计信息?

In Linux where does the netstat -su command get the statistics?

在我的 linux 服务器中,当我 运行 netstat -su 我可以像这样得到 udp 数据包的统计数据:

netstat -su 
IcmpMsg:
    InType0: 10827
    InType3: 42792
    InType8: 298795
    InType13: 2
    OutType0: 298795
    OutType3: 328120
    OutType8: 10827
    OutType14: 2 
Udp:
    232862733 packets received
    12074334 packets to unknown port received.
    555474 packet receive errors
    8650718 packets sent 
UdpLite: IpExt:
    InBcastPkts: 375
    InOctets: 169855997552
    OutOctets: 60497003017
    InBcastOctets: 144080

netstat 命令从哪里得到这些统计数据?我可以清除缓冲区以使它们从零开始吗?

计数器的设计原则上是不能被重置的,如果它们被重置,就违背了它们作为计数器的目的。计数器的要点是数据的消费者可以轮询它们并计算速率,或者计算自某个时间以来的增量,但轮询的频率无关紧要。可能有许多不同的数据消费者,如果计数器下降(比如为零),消费者可以丢弃数据周期或假设他们已经滚动(可能导致错误报告)。

不过,您可以将它们与您自己的消费者一起重新设置基准(例如,运行 获取统计信息、查看其当前值并提供扣除这些初始值的后续读数的脚本)。

您无需离开终端即可找到此类问题的答案。

让我们自己看看:

# strace netstat -su &> netstat_strace

它将是一个 'open' 和 'read' 因为它从某个地方获取数据(但是 grep 出它失败的地方 read/open):

# grep -E 'open|read' netstat_strace  | grep -v ENOENT
open("/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
open("/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
read(3, "7ELF[=11=][=11=][=11=][=11=][=11=][=11=][=11=][=11=][=11=][=11=]>[=11=][=11=][=11=][=11=]0[=11=][=11=][=11=][=11=][=11=]"..., 832) = 832
open("/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
open("/proc/meminfo", O_RDONLY|O_CLOEXEC) = 3
read(3, "MemTotal:        3854816 kB\nMemF"..., 1024) = 1024
open("/proc/net/snmp", O_RDONLY)        = 3
read(3, "Ip: Forwarding DefaultTTL InRece"..., 4096) = 1261
open("/usr/share/locale/locale.alias", O_RDONLY|O_CLOEXEC) = 4
read(4, "# Locale name alias data base.\n#"..., 4096) = 2570
read(4, "", 4096)                       = 0
read(3, "", 4096)                       = 0
open("/proc/net/netstat", O_RDONLY)     = 3
read(3, "TcpExt: SyncookiesSent Syncookie"..., 4096) = 2158
read(3, "", 4096)                       = 0

并且通过检查 strace 输出,我们可以看到它正在写入一个字符串:

write(1, "IcmpMsg:\n    InType0: 11\n    InT"..., 373IcmpMsg:
    InType0: 11

嗯,这很有趣。让我们查看 netstat:

的手册页
man netstat

如果你在 FILES 下查看:

FILES

   /etc/services -- The services translation file

   /proc -- Mount point for the proc filesystem, which gives access to kernel status information via the following files.

   /proc/net/dev -- device information

   /proc/net/raw -- raw socket information

   /proc/net/tcp -- TCP socket information

   /proc/net/udp -- UDP socket information

   /proc/net/igmp -- IGMP multicast information

...

您可以从上面看到 opened 和 read 的原因。在搜索 'clear' 或 'reset'(或阅读它)时,您会发现这些不是命令的选项。

下一步将检查 man proc,它自称是 "process information pseudo-filesystem."

从这里,您可以了解到,如果您修改了 netstat 从中读取的文件,则可以更改 netstat 的输出(/proc/net/netstat 在我看来特别有趣)——而且您可以—— - 但我建议只读。