1

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.

Community
  • 1
  • 1
samthebest
  • 30,803
  • 25
  • 102
  • 142

1 Answers1

3

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.

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
samthebest
  • 30,803
  • 25
  • 102
  • 142
  • Interesting... If I give an octet with a leading zero to "ping" (both on Linux or Windows) or enter it into a browser, it treats that octet as an octal number! So if I tell my browser to go to 176.040.0142.166 it goes to 176.32.98.166 (amazon.com). So if you and Wikipedia are right about the standard, a lot of other tools are acting in a non-standard way. I see that the Wikipedia article mentions that... – ajb Aug 07 '14 at 20:33
  • Yup, it's confusing! - and frustratingly so given it's such a foundational concept! @ajb – samthebest Aug 07 '14 at 20:46