Is an IP address with an octet given by 4 or more zeros a valid IP address?

三世轮回 提交于 2019-12-11 11:26:27

问题


The top voted answer for validating IP addresses here (which is a regex, so automatically unfavourable) returns false if you give it an IP address with 4 or more zeros in a single octet.

Note that it passes with 3 or less, which in my opinion, automatically indicates code smell due to arbitrary inconsistency (after all it's not base 8 and so there is nothing special about 3 in base 10). Nevertheless, surprisingly the apache commons utility InetAddressValidator also has this behaviour (at least it only uses regex for the splitting!).

Observe (using Scala REPL):

scala> new InetAddressValidator().isValidInet4Address("000.0.0.0")
res0: Boolean = true

scala> new InetAddressValidator().isValidInet4Address("0000.0.0.0")
res1: Boolean = false

Now this answer would return true, as it's using parseInt in a loop which makes no arbitrary distinction between numbers of zeros.

So is it valid? If it is valid then this indicates a bug in Apache Commons library and the said regex, and if it is NOT valid then please provide a link to something that proves it.


回答1:


Yes, it is valid.

An except from Wikipedia article on Dot-decimal notation about IPv4 address:

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.

A valid decimal number may or may not start with leading 0's and there should be no intrinsic restriction to the number of leading 0's. The wiki page does indeed clarify that leading 0's are valid, but does not explicitly mention any limit on the number of leading zeros.



来源:https://stackoverflow.com/questions/25191349/is-an-ip-address-with-an-octet-given-by-4-or-more-zeros-a-valid-ip-address

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!