top voted answer用于验证此处的 IP 地址(这是一个正则表达式,因此自动不受欢迎)如果您给它一个在单个八位字节中包含 4 个或更多零的 IP 地址,则返回 false。
请注意,它以 3 或更少的值通过,在我看来,这会自动指示由于任意不一致而导致的代码异味(毕竟它不是以 8 为基数,因此以 10 为基数的 3 没有什么特别之处)。然而,令人惊讶的是,apache 公共(public)实用程序 InetAddressValidator
也有这种行为(至少它只使用正则表达式进行拆分!)。
观察(使用 Scala REPL):
scala> new InetAddressValidator().isValidInet4Address("000.0.0.0")
res0: Boolean = true
scala> new InetAddressValidator().isValidInet4Address("0000.0.0.0")
res1: Boolean = false
现在this answer将返回 true,因为它在一个循环中使用 parseInt
,它不会任意区分零的数量。
那么它有效吗?如果有效,则表明 Apache Commons 库和所述正则表达式中存在错误,如果无效,则请提供指向证明它的内容的链接。
最佳答案
是的,它是有效的。
来自 Wikipedia article on Dot-decimal notation 的除外关于 IPv4 地址:
An Internet Protocol Version 4 (IPv4) address consists of 32 bits, which may be divided into four octets, 8 bits each. These four octets are written in decimal numbers, ranging from 0 to 255, and are concatenated as a character string with full stop delimiters between number.
有效的十进制数字可能以也可能不以前导 0 开头,并且对前导 0 的数量应该没有内在限制。 wiki 页面确实阐明了前导 0 是有效的,但没有明确提及对前导零数量的任何限制。
关于java - 八位字节由 4 个或更多零给出的 IP 地址是否为有效 IP 地址?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25191349/