ping 零是如何工作的?

ping 零是如何工作的?

任何人都可以解释它是如何ping 0工作的并将其转换为127.0.0.1.

[champu@testsrv ]$ ping 0
PING 0 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.039 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.013 ms

--- 0 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1000ms
rtt min/avg/max/mdev = 0.013/0.026/0.039/0.013 ms

答案1

特殊(和 AFAICT)行为的记录略有不足iputils ping: 你自己ping一下。

如果您ping 0遇到这种情况(为了清晰起见,进行了大量编辑和评论):

if (inet_aton(target, &whereto.sin_addr)) == 1) {
    // convert string to binary in_addr
}
// inet_aton returns 1 (success) and leaves the `in_addr` contents all zero.

if (source.sin_addr.s_addr == 0) {    
    // determine IP address of src interface, via UDP connect(), getsockname()
}

// special case for 0 dst address
if (whereto.sin_addr.s_addr == 0)
        whereto.sin_addr.s_addr = source.sin_addr.s_addr;

inet_aton()不是 POSIX,但我假设它复制了inet_addr()当转换的点分小数少于 4 个时。对于无点单个数字,它只是存储到二进制网络地址中,0x00000000相当于点分形式0.0.0.0

strace如果您(作为 root)可以看到这一点:

# strace -e trace=network ping  0
socket(PF_INET, SOCK_RAW, IPPROTO_ICMP) = 3
socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 4
connect(4, {sa_family=AF_INET, sin_port=htons(1025), 
    sin_addr=inet_addr("0.0.0.0")}, 16) = 0
getsockname(4, {sa_family=AF_INET, sin_port=htons(58056),   
    sin_addr=inet_addr("127.0.0.1")}, [16]) = 0
...
PING 0 (127.0.0.1) 56(84) bytes of data.

如果您绑定到具体的接口改为:

# strace -e trace=network ping -I eth0  0
socket(PF_INET, SOCK_RAW, IPPROTO_ICMP) = 3
socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 4
setsockopt(4, SOL_SOCKET, SO_BINDTODEVICE, "eth0\0", 5) = 0
connect(4, {sa_family=AF_INET, sin_port=htons(1025), 
    sin_addr=inet_addr("0.0.0.0")}, 16) = 0
getsockname(4, {sa_family=AF_INET, sin_port=htons(58408),    
    sin_addr=inet_addr("192.168.0.123")}, [16]) = 0
setsockopt(3, SOL_RAW, ICMP_FILTER,  ...)
[...]
PING 0 (192.168.0.123) from 192.168.0.123 eth0: 56(84) bytes of data.

而在许多情况下 0 可能被视为 0.0.0.0 和广播地址这显然不是 ping 正在做的事情。它在特殊情况下表示“相关接口的主要 IP”(对多播/广播情况进行一些额外处理)。

RFC 1122§3.2.1.3 解释了这种行为:0.0.0.0 和网络屏蔽的 IP 地址(“主机号”,例如环回情况下的 0.0.0.1)都意味着“该网络上的该主机”。

       (a)  { 0, 0 }

            This host on this network.  MUST NOT be sent, except as
            a source address as part of an initialization procedure
            by which the host learns its own IP address.

            See also Section 3.3.6 for a non-standard use of {0,0}.

       (b)  { 0, <Host-number> }

            Specified host on this network.  It MUST NOT be sent,
            except as a source address as part of an initialization
            procedure by which the host learns its full IP address.

至少在 0 或 0.0.0.0 的情况下,iputils 的ping行为方式是这样的,其他 ping 和其他操作系统的行为可能有所不同。例如,FreeBSD 通过默认路由 ping 0.0.0.0(我认为这不是“正确”的行为)。

ping 1或者0.0.0.1不太像希望的那样工作(无论如何不适合我,iputils-sss20101006)。

相关内容