为什么 /proc/net/tcp6 将 ::1 表示为 ::100:0

gre*_*ift 13 linux ipv6 linux-kernel

我正在编写一个实用程序来检查 /proc/net/tcp 和 tcp6 的活动连接,因为它比解析 netstat 输出更快。

因为我实际上没有启用 ipv6,所以我主要使用 localhost 作为我的参考点。这是我的 /proc/net/tcp6 的副本

sl  local_address                         remote_address                        st tx_queue rx_queue tr tm->when retrnsmt   uid  timeout inode
 0: 00000000000000000000000000000000:006F 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 19587 1 ffff880262630000 100 0 0 10 -1
 1: 00000000000000000000000000000000:0050 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 22011 1 ffff880261c887c0 100 0 0 10 -1
 2: 00000000000000000000000000000000:0016 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 21958 1 ffff880261c88000 100 0 0 10 -1
 3: 00000000000000000000000001000000:0277 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000     0        0 28592 1 ffff88024eea0000 100 0 0 10 -1
Run Code Online (Sandbox Code Playgroud)

这是匹配的 netstat -6 -pant

Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name    
tcp6       0      0 :::111                  :::*                    LISTEN      -                   
tcp6       0      0 :::80                   :::*                    LISTEN      -                   
tcp6       0      0 :::22                   :::*                    LISTEN      -                   
tcp6       0      0 ::1:631                 :::*                    LISTEN      -      
Run Code Online (Sandbox Code Playgroud)

tcp6 中的条目 0-3 对应于 ::'s(所有 ipv6),但条目 4 应该是 ::1 的对应条目。

这就是我困惑的地方...

00000000000000000000000001000000 => 0000:0000:0000:0000:0000:0000:0100:0000 => ::100:0

当我通过一些代码运行 ::1 以生成完整的十六进制表示时,我得到:

import binascii
import socket
print binascii.hexlify(socket.inet_pton(socket.AF_INET6, '::1'))
00000000000000000000000000000001
Run Code Online (Sandbox Code Playgroud)

我无法以编程方式将这两个值对齐,因为它们不匹配(显然)。他们为什么不匹配?为什么内核认为 ::100:0 是 ::1?

kas*_*erd 11

这是由于/proc/net/tcp6. 地址作为四个字处理,每个字由四个字节组成。在这四个字的每一个中,四个字节以相反的顺序写入。

2001:0db8       :: 0123:4567:89ab:cdef would thus come out as:
B80D 0120 00000000 6745 2301 EFCD AB89 (with spaces inserted for clarity).
Run Code Online (Sandbox Code Playgroud)

这可能是由于字节序差异造成的。现在大多数 PC 都使用 IA32 或 AMD64,它们使用的字节序与 IP 设计的字节序相反。我没有任何其他系统可以测试以确定您是否可以依赖 /proc/net/tcp6 总是看起来像那样。但我证实在 IA32 和 AMD64 架构上都是这种情况。