Not with a regex!

Most of this discussion is about IP version 4 (IPv4) addresses. We’ll talk about IPv6 a bit later.

An IPv4 address is a 32bit number, every other representation is just a convenient display of that number. When you’re dealing with a dotted quad or any other notation for an IP address, you’re usually better off getting it back to its numeric true form as quickly as you can. You definitely don’t want to do any of the sort of routing math your network stack is doing directly on a dotted quad.

Before you think you need to go parse it yourself with your bulletproof™ regex, realize that parsing IPv4 addresses has been there in just about every language, stack, and implementation since the internet protocol got going. Just look at the manual entries for inet_aton and inet_ntoa, they predate some licensed drivers these days, or any of the more modern alternatives.

So, still think you can parse an IPv4 with a regex? Internet failures, sometimes at colossal scale, occur at alarming intervals with that sort of thinking. Ready?

Let’s start with the dotted quad, as most people know it today: AAA.BBB.CCC.DDD Where AAA, BBB, CCC, and DDD are numbers from 0 to 255 (8 bits / an octet / the common byte nowadays), inclusive.

  • That’s the first common failure. 0..255. Not 0..999 for each entry.
  • What about spaces? is 10.2 0.30.40 valid? Oh, we can just remove the whitespaces if the user accidentally entered that, just make sure your 8bit test comes after cleanup.
  • Due to standards disagreements at the time, Octal is a valid IP. Java will honor it in the default implementation with any leading zero. 01.02.03.09 is going to throw due to an invalid octal sequence. Did you remember to check that? And before you say this doesn’t happen anymore, I watched this take down Netflix when a vendor accidentally inserted a zero ahead of a 9 in an IP address that was imported.
  • Did you know you could use hex? FE.1D.23.42 is a valid IPv4 on a number of implementations, and there’s no place like 0x7F.1
  • Should you assume all other parts of the quad follow the same numeric format once you see a hex digit or an octal signifier?

Here’s a better idea. Use the platform library that knows how to parse everything for you, often without a regex.

Let’s not talk about all the “special” parts of the IPv4 address space as well.

IPv6 did not have anyone clamoring hard at the standards fights for octal representation formats and there was passing familiarity with how many things could go wrong with a loosely defined standard for the non-numeric representations. The standard also came into use long after high quality open source versions of the parsers were already available, so there weren’t any strange licensing payments to use a version that “just worked”.