Ip

缺少的 0 是如何自動添加到 IP 地址中的?(ping 10.5 相當於ping 10.0.0.5

  • July 4, 2014

我不小心輸入了

ssh 10.0.05

代替

ssh 10.0.0.5

並對它起作用感到非常驚訝。我也試過10.005and10.5那些也自動擴展為10.0.0.5. 我也嘗試過192.168.1並將其擴展到192.168.0.1. 所有這些也適用於ping而不是ssh,所以我懷疑它適用於連接到任意使用者提供的主機的許多其他命令。

為什麼這行得通?這種行為是否記錄在某處?這種行為是 POSIX 的一部分還是什麼?還是只是一些奇怪的實現?(使用 Ubuntu 13.10 值得。)

引自man 3 inet_aton

  a.b.c.d   Each of the four numeric parts specifies a byte of the
            address; the bytes are assigned in left-to-right order to
            produce the binary address.

  a.b.c     Parts a and b specify the first two bytes of the binary
            address.  Part c is interpreted as a 16-bit value that
            defines the rightmost two bytes of the binary address.
            This notation is suitable for specifying (outmoded) Class B
            network addresses.

  a.b       Part a specifies the first byte of the binary address.
            Part b is interpreted as a 24-bit value that defines the
            rightmost three bytes of the binary address.  This notation
            is suitable for specifying (outmoded) Class C network
            addresses.

  a         The value a is interpreted as a 32-bit value that is stored
            directly into the binary address without any byte
            rearrangement.

  In all of the above forms, components of the dotted address can be
  specified in decimal, octal (with a leading 0), or hexadecimal, with
  a leading 0X).  Addresses in any of these forms are collectively
  termed IPV4 numbers-and-dots notation.  The form that uses exactly
  four decimal numbers is referred to as IPv4 dotted-decimal notation
  (or sometimes: IPv4 dotted-quad notation).

為了好玩,試試這個:

$ nslookup unix.stackexchange.com
Non-authoritative answer:
Name:   unix.stackexchange.com
Address: 198.252.206.140

$ echo $(( (198 << 24) | (252 << 16) | (206 << 8) | 140 ))
3338456716

$ ping 3338456716         # What?  What did we ping just now?
PING stackoverflow.com (198.252.206.140): 48 data bytes
64 bytes from 198.252.206.140: icmp_seq=0 ttl=52 time=75.320 ms
64 bytes from 198.252.206.140: icmp_seq=1 ttl=52 time=76.966 ms
64 bytes from 198.252.206.140: icmp_seq=2 ttl=52 time=75.474 ms

引用自:https://unix.stackexchange.com/questions/120157